Search code examples
phparraysobjectfilteringearly-return

Most efficient way to search for object in an array by a specific property's value


What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];

What do I write inside of:

function findObjectById($id){

}

The desired result would return the object at $array[0] if I called:

$obj = findObjectById('one')

Otherwise, it would return false if I passed 'four' as the parameter.


Solution

  • You can iterate that objects:

    function findObjectById($id){
        $array = array( /* your array of objects */ );
    
        foreach ( $array as $element ) {
            if ( $id == $element->id ) {
                return $element;
            }
        }
    
        return false;
    }
    

    Faster way is to have an array with keys equals to objects' ids (if unique);

    Then you can build your function as follow:

    function findObjectById($id){
        $array = array( /* your array of objects with ids as keys */ );
    
        if ( isset( $array[$id] ) ) {
            return $array[$id];
        }
    
        return false;
    }