Page 1 of 1

Insert array keys into a variable

Posted: Thu Jun 26, 2008 10:04 pm
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.

Re: Insert array keys into a variable

Posted: Thu Jun 26, 2008 10:10 pm
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.

Re: Insert array keys into a variable

Posted: Thu Jun 26, 2008 10:19 pm
by katlis
Thanks a million, that was so much easier!