[英]Compare Positions of Values in Php Array
$commands = array();
for($p = 0; $p < $commandCount ; $p++){
$commands[$p] = $_POST['select'.$p];
}
所以我有這個Array $命令。 在此Array中,存儲了一個命令列表。 我必須檢查命令“mark”存儲在哪個位置,以及后面是否有某個命令。 一些示例數據可以在$命令中:“mark”,“ignore”,“pick”,“random”你會怎么做?
你可以使用$index = array_search("mark", $commands)
來返回第一次出現命令“mark”的索引,然后你可以使用$commands[$index + 1]
來獲取下一個命令。陣列。
您還需要檢查$index != null
,否則它可能會返回$commands
數組中的第一項,因為null
被解釋為0
這是一個帶有一組測試用例的演示,以充分表達它的工作原理並識別邊緣情況:( 演示鏈接 )
*注意,當找不到針時, array_search()
返回false
。
$commands = array("mark", "ignore", "pick", "random");
$attempts = array("mark", "ignore", "pick", "random", "bonk");
foreach($attempts as $attempt){
echo "$attempt => ";
$index=array_search($attempt,$commands);
// vv---increment the value
if($index===false || !isset($commands[++$index])){ // not found or found last element
$index=0; // use first element
}
echo $commands[$index],"\n";
}
“或”( ||
)條件將“短路”,因此如果$index
為false
,它將退出條件而不調用第二個表達式( isset()
)。
輸出:
mark => ignore
ignore => pick
pick => random
random => mark
bonk => mark
剛做了一些雙重檢查,你要先斷言你的數組首先包含mark的值。 否則array_search將返回false,並且很容易將其轉換為0。
支持文檔 :
$commands = array("mark", "ignore", "pick", "random");
//checks if $command contains mark,
//gets first index as per documentation
//Or sets index to -1, ie No such value exists.
$index = in_array("mark",$commands) ? array_search("mark",$commands):-1;
//gets the next command if it exists
$nextCommand = $index!=-1? $commands[++$index]:"Unable to Find Command: mark";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.