2

I'm sure there is an easy way to do this, but I can't think of it right now. Is there an array function or something that lets me search through an array and find the item that has a certain property value? For example:

$people = array(
  array(
    'name' => 'Alice',
    'age' => 25,
  ),
  array(
    'name' => 'Waldo',
    'age' => 89,
  ),
  array(
    'name' => 'Bob',
    'age' => 27,
  ),
);

How can I find and get Waldo?

3 Answers 3

1

With the following snippet you have a general idea how to do it:

foreach ($people as $i => $person)
{
    if (array_key_exists('name', $person) && $person['name'] == 'Waldo')
        echo('Waldo found at ' . $i);
}

Then you can make the previous snippet as a general use function like:

function SearchArray($array, $searchIndex, $searchValue)
{
    if (!is_array($array) || $searchIndex == '')
        return false;

    foreach ($array as $k => $v)
    {
        if (is_array($v) && array_key_exists($searchIndex, $v) && $v[$searchIndex] == $searchValue)
            return $k;
    }

    return false;
}

And use it like this:

$foundIndex = SearchArray($people, 'name', 'Waldo'); //Search by name
$foundIndex = SearchArray($people, 'age', 89); //Search by age

But watch out as the function can return 0 and false which both evaluates to false (use something like if ($foundIndex !== false) or if ($foundIndex === false)).

Sign up to request clarification or add additional context in comments.

2 Comments

Nice function. Think I would declare the function as function SearchArray(array $array, ... and skip the is_array check though =)
I know there is no other option, but still stupid that you really need to loop though the data.
0
function findByName($array, $name) {
    foreach ($array as $person) {
        if ($person['name'] == $name) {
            return $person;
        }
    }
}

Comments

0
function getCustomSearch($key) {
   foreach($people as $p) {
      if($p['name']==$searchKey) return $p
   }
}

getCustomSearch('waldo');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.