Insert array keys into a variable

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
katlis
Forum Newbie
Posts: 10
Joined: Mon Nov 05, 2007 12:42 pm

Insert array keys into a variable

Post by katlis »

I have an array ($zips) that looks like this:

Array ( [90210] => 0 [90209] => 1.58 [90069] => 1.75 [90212] => 1.86 [90067] => 1.99)

I don't care about the values (miles). I need to use the keys (zip codes) to sort through a MySQL table. This is what I want to accomplish:

$sql = "SELECT * FROM users WHERE zip='90210' OR zip='20209' OR zip='90069' OR zip='90212' OR zip='90067'";

So I was thinking of doing something like:
$possible_zipcodes = "WHERE zip='90210' OR zip='20209' OR zip='90069' OR zip='90212' OR zip='90067'";
$sql = "SELECT * FROM users $possible_zipcodes";

Any idea on how to do this? Or is there another way (I'm sure i'm doing this completely the wrong way)? Any help is greatly appreciated.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Insert array keys into a variable

Post by John Cartwright »

Code: Select all

$zips = array(90210 => 0, 90209 => 1.58, 90212 => 1.86, 90067 => 1.99);
 
$sql = "SELECT * FROM users WHERE zip IN(". implode(',', array_keys($zips)).")";
 
echo $sql .'<br />';
As shown, using mysql's IN() clause (instead of repeated OR's), creating a comma seperated list with implode() on array_keys() zip code array.
katlis
Forum Newbie
Posts: 10
Joined: Mon Nov 05, 2007 12:42 pm

Re: Insert array keys into a variable

Post by katlis »

Thanks a million, that was so much easier!
Post Reply