Below is my array. Assuming I know the current array key (say 53), how do I get the adjacent/next array key which is not in sequence? I can't use current()
, can I?
(
[50] => Array
(
[product_id] => 50
[unit] => 1
)
[53] => Array
(
[product_id] => 53
[unit] => 1
)
[58] => Array
(
[product_id] => 58
[unit] => 1
)
)
CodePudding user response:
You can get the keys and the values as an array with array_keys()
and array_values()
respectively. Now use array_search()
to get the index of the key (53).
You can then increase the index by 1 which will be the index of the next key. Once you know the index of the next key, you can use it to get its corresponding value as well. Try this
$array = array(
'50' => array(
'product_id' => 50,
'unit' => 1
),
'53' => array(
'product_id' => 53,
'unit' => 1
),
'58' => array(
'product_id' => 58,
'unit' => 1
),
);
$current_index = array_search('53', array_keys($array));
$next_array = array_values($array)[$current_index 1];
print_r($next_array);