Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of value in associative array in php?

Tags:

loops

php

If you have any array $p that you populated in a loop like so:

$p[] = array( "id"=>$id, "Name"=>$name);

What's the fastest way to search for John in the Name key, and if found, return the $p index? Is there a way other than looping through $p?

I have up to 5000 names to find in $p, and $p can also potentially contain 5000 rows. Currently I loop through $p looking for each name, and if found, parse it (and add it to another array), splice the row out of $p, and break 1, ready to start searching for the next of the 5000 names.

I was wondering if there if a faster way to get the index rather than looping through $p eg an isset type way?

Thanks for taking a look guys.

like image 957
Shaun Avatar asked Oct 14 '13 10:10

Shaun


2 Answers

Okay so as I see this problem, you have unique ids, but the names may not be unique.

You could initialize the array as:

array($id=>$name);

And your searches can be like:

array_search($name,$arr);

This will work very well as native method of finding a needle in a haystack will have a better implementation than your own implementation.

e.g.

$id = 2;
$name= 'Sunny';
$arr = array($id=>$name);
echo array_search($name,$arr);

Echoes 2

The major advantage in this method would be code readability.

like image 140
Sunny R Gupta Avatar answered Oct 10 '22 14:10

Sunny R Gupta


If you know that you are going to need to perform many of these types of search within the same request then you can create an index array from them. This will loop through the array once per index you need to create.

$piName = array();
foreach ($p as $k=>$v)
{
  $piName[$v['Name']] = $k;
}

If you only need to perform one or two searches per page then consider moving the array into an external database, and creating the index there.

like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 10 '22 14:10

Ignacio Vazquez-Abrams