Jacob
Jacob

Reputation: 422

PHP: Search objects in an array

Let's say I have an array of objects.

<?php

$people = array();
$people[] = new person('Walter Cook');
$people[] = new person('Amy Green');
$people[] = new person('Irene Smith');

How can I search an object in this array for a certain instance variable? For example, let's say I wanted to search for a person object with the name of "Walter Cook".

Thanks in advance!

Upvotes: 0

Views: 1893

Answers (4)

aemad
aemad

Reputation: 111

well you could try this inside your class

    //the search function
function search_array($array, $attr_name, $attr_value) {
    foreach ($array as $element) {
        if ($element -> $attr_name == $attr_value) {
            return TRUE;
        }
    }
    return FALSE;
}

//this function will test the output of the search_array function
function test_Search_array() {
    $person1 = new stdClass();
    $person1 -> name = 'John';
    $person1 -> age = 21;

    $person2 = new stdClass();
    $person2 -> name = 'Smith';
    $person2 -> age = 22;
    $test = array($person1, $person2);
    //upper/lower case should be the same
    $result = $this -> search_array($test, 'name', 'John');
    echo json_encode($result);
}

Upvotes: 0

Darragh Enright
Darragh Enright

Reputation: 14136

Assuming that name is a public property of the person class:

<?php

// build the array of objects
$people = array();
$people[] = new person('Walter Cook');
$people[] = new person('Amy Green');
$people[] = new person('Irene Smith');

// search name
$searchName = 'Walter Cook';

// ascertain the presence of the name in the array of objects
$isMatch = false;

foreach ($people as $person) {
    if ($person->name === $searchName) {
        $isMatch = true;
        break;
    }
}

// alternatively, if you want to return all matches into 
// a new array of $results you can use array_filter
$result = array_filter($people, function($person) use ($searchName) {
    return $person->name === $searchName;
});

hope this helps :)

Upvotes: 1

kfinto
kfinto

Reputation: 301

It depends of the person class construction, but if it has a field name that keeps given names, you can get this object with a loop like this:

for($i = 0; $i < count($people); $i++) {
    if($people[$i]->name == $search_name) {
        $person = $people[$i];
        break;
    }
}

Upvotes: 4

Wagner Leonardi
Wagner Leonardi

Reputation: 4446

Here is:

$requiredPerson = null;

for($i=0;$i<sizeof($people);$i++)
{
   if($people[$i]->name == "Walter Cook")
    {
        $requiredPerson = $people[$i];
        break;
    }

}

if($requiredPerson == null)
{
    //no person found with required property
}else{
    //person found :)
}

?>

Upvotes: 2

Related Questions