While developing a new project management application I needed a way to search an array of objects for a specific object property value. For example, I had an array of “employee” objects that contain a great many properties to describe each “employee” and you want to search this array for an employee object that has a specific value for one of it’s properties. To solve this I have come up with the following little snippet:
function search_object_array($needle_key, $needle_val, $haystack)
{
// iterate through our haystack
for ( $i = 0; $i < count($haystack); $i++ )
{
// ensure this array element is an object and has a key that matches our needle's key
if ( is_object($haystack[$i]) and property_exists($haystack[$i], $needle_key) )
{
// determine if comparison is case sensitive
if ( strtolower($needle_val) == strtolower($haystack[$i]->$needle_key) ) return $i;
}
}
// no match found
return false;
}
This function returns the index of the object array if a match is found and false if no matches are found.
So lets test it.
First I’ll define a class that we will use to generate our objects that will populate our array, well call this class “foo”.
class foo
{
public $id;
public $name;
public $description;
public function __construct( $id, $name, $description )
{
$this->id = $id;
$this->name = $name;
$this->description = $description;
}
}
Next we’ll populate our object array “$obj_arr” with objects
$obj_arr[0] = new foo(1, 'Joe', 'Joes description');
$obj_arr[1] = new foo(2, 'Sara', 'Saras description');
$obj_arr[2] = new foo(3, 'Adam', 'Adams description');
$obj_arr[3] = new foo(4, 'Jake', 'Jakes description');
$obj_arr[4] = new foo(5, 'Sally', 'Sallys description');
$obj_arr[5] = new foo(6, 'Paul', 'Pauls description');
$obj_arr[6] = new foo(7, 'Freddie', 'Freddies description');
Now lets search our new array of objects for an object that matches our criteria:
$result = search_object_array('name', 'sally', $obj_arr);
echo $result;
// will print: 4
I hope this helps!