Search code examples
phparraysarray-key

Finding the next array row with PHP


I'm working in a code that find the next array value based on the current value but still always returning 1 as result.

$users_emails = array('Spence', 'Matt', 'Marc', 'Adam', 'Paul');

$current = 'Spence';
$keys = array_keys($users_emails);
$ordinal = (array_search($current,$keys)+1);
$next = $keys[$ordinal];
echo $next;

What's wrong?


Solution

  • $keys are the keys, not the value. Use the array with the $ordinal.

    $next = $users_emails[$ordinal];
    

    Demo: https://3v4l.org/REhGr

    The array_keys gives you an array of the keys. Use your normal array for the array_search as well. Here's a visual of what you currently are building for $keys.

    Array
    (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
    )
    

    Demo: https://3v4l.org/GQQcF

    $users_emails = array('Spence', 'Matt', 'Marc', 'Adam', 'Paul');
    $current = 'Marc';
    $ordinal = (array_search($current, $users_emails)+1);
    $next = !empty($users_emails[$ordinal]) ? $users_emails[$ordinal] : FALSE;
    echo $next;