Having an array similar to the one below:
$steps = array(0 => 'aaa', 1 => 'bbb', 2 => 'ccc', ......, 7 => 'hhh', 8 => 'iii', .....);
How can I calculate how many steps (key) do I need to reach key 2 from key 7 respecting the sequence?
Having an array similar to the one below:
$steps = array(0 => 'aaa', 1 => 'bbb', 2 => 'ccc', ......, 7 => 'hhh', 8 => 'iii', .....);
How can I calculate how many steps (key) do I need to reach key 2 from key 7 respecting the sequence?
If you have numeric keys that never have any missing numbers, you can use basic subtraction.
If you need to account for possible missing numbers, or the keys are not numeric, you can use a combination of array_keys()
and array_search()
:
$array = array(
0 => 'aaa',
1 => 'bbb',
3 => 'ccc',
'four' => 'ddd',
900 => 'eee',
13 => 'fff'
);
$from = 1;
$to = 900;
$keys = array_keys($array);
$from_index = array_search($from, $keys); // 1
$to_index = array_search($to, $keys); // 4
$steps = $to_index - $from_index;
// 3 steps: from 1-3, from 3-'four' and from 'four'-900