PHP Find Next Element by Object Property in Array

Published 10th January 2014

This one tripped me up recently. Say you need to find the next element in an array based on an object property. So you might have an array like:

Array ( [0] => stdClass Object ( [id] => 65, ... ) [1] => stdClass Object ( [id] => 66, ... ) ... )

And you need to find the object after the object with an ID of 66. This is how you do it:

$next_element = false; reset($array); while($current_element = current($array)){ if($current_element->id == $object_id) break; next($array); } $next_element = next($array);

In the above code $object_id is the ID of the object before the object that you want to find. Make sure you reset() the array before looping through it otherwise you might miss the first element.