How can I get previous and next element of array based on current element?

here is my sample

                      Array
(
    [0] => stdClass Object
        (
            [id] => 4
        )

    [1] => stdClass Object
        (
            [id] => 3
        )

    [2] => stdClass Object
        (
            [id] => 2
        )

    [3] => stdClass Object
        (
            [id] => 1
        )
      }
  • I am getting an id = 3 on my page , how can I get previous and next id based on id I am getting on my page using the above array
function getPreviousAndNext($rows, $current): array
{
    $ids = array_map(
        static function($row) {
            return $row->id;
        },
        $rows
    );

    $currentIndex = array_search($current, $ids);
    if (false === $currentIndex) {
        // current not found in rows, unable to determine
        // previous and next
        return [null, null]; 
    }

    return [
        $ids[$currentIndex - 1] ?? null,
        $ids[$currentIndex + 1] ?? null,
    ];
}

See https://repl.it/repls/PointlessImpeccableType for a working example of how to use it :slight_smile:

Dont reinvent the wheel, Ramon :wink:

$ids = array_column($rows,'id');

I though about that, but that only works on assoc arrays, no? The OP has an array of objects with public properties.

Edit: turns out it works on arrays with objects that have public properties as well. Never knew that. So yes. That would be shorter :slightly_smiling_face:

As of PHP 7, yup :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.