-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

2

2 Answers 2

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 ] : "");
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.