[英]How to get Next or Previous Array Value Based On Value PHP
i have a code like this : 我有这样的代码:
$step_master = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$step_now = 4;
$step_before = ????;
$step_next = ????;
how can i get the next value or the previous value from the $step_now
in $step_master
我如何从
$step_now
中的$step_master
获取下一个值或上一个值
so the output should be like this : 所以输出应该是这样的:
Now : 4
Previous : 3
Next : 5
i've tried using next()
but it don't have another parameter for $step_now
我尝试使用
next()
但没有$step_now
另一个参数
any help will be appreciated 任何帮助将不胜感激
thanks 谢谢
You can use array_search
to get current key. 您可以使用
array_search
获取当前密钥。 Then iterate towards previous or next step 然后迭代到上一步或下一步
$step_master = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$step_now = 4;
$now_index = array_search($step_now,$step_master);
echo "Now = ".$step_now ;
echo "Previous =".(isset($step_master[$now_index - 1])?$step_master[$now_index -1 ] : "");
echo "Next =".(isset($step_master[$now_index +1 ])?$step_master[$now_index +1 ] : "");
$step_master = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$step_now = 4;
$index = array_search($step_now, $step_master);
$step_before = ($index > 0) ? $step_master[$index-1] : null;
$step_next = ($index < count($step_master)) ? $step_master[$index+1] : null;
echo var_dump($step_before, $step_next);
pretty oldschool but works 漂亮的老式,但工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.