[英]Compare Positions of Values in Php Array
$commands = array();
for($p = 0; $p < $commandCount ; $p++){
$commands[$p] = $_POST['select'.$p];
}
So I have this Array $commands. 所以我有这个Array $命令。 In this Array, a List of Commands is stored.
在此Array中,存储了一个命令列表。 I have to check on which Position the Command "mark" is stored and if a certain command follows after it.
我必须检查命令“mark”存储在哪个位置,以及后面是否有某个命令。 Some Example Data which can be in $commands: "mark", "ignore", "pick", "random" How would You do it?
一些示例数据可以在$命令中:“mark”,“ignore”,“pick”,“random”你会怎么做?
You can use $index = array_search("mark", $commands)
which will return the index of the first occurrence of the command "mark" and then you can use $commands[$index + 1]
to get the next command in the array. 你可以使用
$index = array_search("mark", $commands)
来返回第一次出现命令“mark”的索引,然后你可以使用$commands[$index + 1]
来获取下一个命令。阵列。
You will also need to check if $index != null
as otherwise it may return the first item in your $commands
array because null
is interpreted as 0 您还需要检查
$index != null
,否则它可能会返回$commands
数组中的第一项,因为null
被解释为0
Here is a demonstration with a battery of test cases to fully express how it works and identify fringe cases: ( Demo Link ) 这是一个带有一组测试用例的演示,以充分表达它的工作原理并识别边缘情况:( 演示链接 )
*note, array_search()
returns false
when the needle is not found. *注意,当找不到针时,
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";
}
The "or" ( ||
) condition will "short circuit", so if $index
is false
it will exit the condition without calling the second expression ( isset()
). “或”(
||
)条件将“短路”,因此如果$index
为false
,它将退出条件而不调用第二个表达式( isset()
)。
Output: 输出:
mark => ignore
ignore => pick
pick => random
random => mark
bonk => mark
Just did some double checking you're going to want to assert first that your array contains the value of mark first. 刚做了一些双重检查,你要先断言你的数组首先包含mark的值。 array_search will return a false otherwise, and that easily can be translated into 0.
否则array_search将返回false,并且很容易将其转换为0。
Supporting Documentation : 支持文档 :
PHP array_search PHP array_search
$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.