-1

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

DarkCode999
  • 182
  • 1
  • 1
  • 11
  • 1
    Possible duplicate of [How to set an Arrays internal pointer to a specific position? PHP/XML](https://stackoverflow.com/questions/795625/how-to-set-an-arrays-internal-pointer-to-a-specific-position-php-xml) – Sahil Gulati Sep 22 '17 at 05:38
  • 4
    Am I missing something? Why isn't it just `$step_before = $step_now - 1;`? – Barmar Sep 22 '17 at 05:39

2 Answers2

5

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 ] : "");
B. Desai
  • 16,414
  • 5
  • 26
  • 47
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

Michael M.
  • 189
  • 1
  • 7