Page 1 of 1

Searching a PHP array

Posted: Wed Dec 10, 2008 4:39 am
by Eric Praline
Hi

I've been looking for a solution to this problem for a while, and now my head's spinning as I can't find anything that looks right!

I have an array similar to below...

Code: Select all

$namesArray = array(
                    array("firstname"=>"John", "lastname"=>"Smith", "email"=>"johnsmith@gmail.com"),
                    array("firstname"=>"Arthur", "lastname"=>"Sixpence", "email"=>"arthur@yahoo.co.uk"),
                    array("firstname"=>"John", "lastname"=>"Green", "email"=>"john.green@yahoo.com"),
                    array("firstname"=>"Dave", "lastname"=>"Smith", "email"=>"d.smith@gmail.com")
)
Now, I'm trying to search the array with a name (values of first and last names are returned from a database query), and return the email address. Most of the solutions I've found so far only look for one value, but I need to check for 2 (ie both first and last names in case of duplicates) - but then I also need to return the email address if a match is found; and I've not found any ways of doing that yet. It's quite possible that there is a solution somewhere on the PHP.net website, but I'm a bit lost with the different array functions.

Anyone got any pointers, please?

Re: Searching a PHP array

Posted: Wed Dec 10, 2008 4:56 am
by aceconcepts
You can use a foreach loop to iterate the array:

Code: Select all

 
//get names from db
  $firstName="ralph";
 
//loop array...and search for $firstName
foreach($namesArray as $valuesArray)
{
  if($valuesArray["firstname"]==$firstName){
    //name exists in array
    //access the email value by referencing the array key: $valuesArray["email"]
  }
}
 

Re: Searching a PHP array

Posted: Wed Dec 10, 2008 5:15 am
by silenceghost
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
if you want to find the value instead of key just do array_flip on that array and do the same process

Re: Searching a PHP array

Posted: Wed Dec 10, 2008 5:51 am
by Eric Praline
aceconcepts wrote:You can use a foreach loop to iterate the array: ...
Wow, how chuffing easy was that? Works like a charm, and so simple - I was expecting some convoluted multi-part array-searching extravaganza!

Brilliant, cheers mucker! Saved me a headache for the rest of the day, thanks again! :D