Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get adjacent array key in PHP if my keys are not in sequence?

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
        )

)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading