Searching a PHP array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Eric Praline
Forum Commoner
Posts: 32
Joined: Wed Aug 29, 2007 8:37 am

Searching a PHP array

Post 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?
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: Searching a PHP array

Post 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"]
  }
}
 
silenceghost
Forum Newbie
Posts: 22
Joined: Sun Oct 19, 2008 3:25 am

Re: Searching a PHP array

Post 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
Eric Praline
Forum Commoner
Posts: 32
Joined: Wed Aug 29, 2007 8:37 am

Re: Searching a PHP array

Post 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
Post Reply