简体   繁体   中英

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

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

any help will be appreciated

thanks

You can use array_search to get current key. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM