PHP Next in an Associative Array…

This might me useful for some people…

If you want to echo the value of the next ‘key->value pair’ in an associative array. You can use:

$keys = array_keys($arr);
echo $arr[$keys[(array_search($key, $keys)+1)]];

Where $arr is the associative array, $keys is the $arr keys as values with numerical keys and $key is the $arr key of the key->value pair prior to the one you want to output.

Explained:

$arr = array(
'12' => 'a',
'14' => 'b',
'20' => 'c',
'23' => 'd'
);

And you want to output the next value after ’14’=>’b’, which would be ‘c’. All you need to do is define $key = 14;

If you want to output the previous to ’14’=>’b’, just change the “+” to a “-“.

PHP Next in an Associative Array…

2 thoughts on “PHP Next in an Associative Array…

Leave a Reply

Your email address will not be published. Required fields are marked *