Forum Moderators: coopster

Message Too Old, No Replies

php foreach statement help

         

tec4

10:32 pm on Sep 7, 2011 (gmt 0)

10+ Year Member



Hello Everyone,

I essentially am trying to figure out how to print out all of the zip codes that are associated with a search that I am doing, but not list the same zip code more than once. My current foreach statement is as follows and prints out the zip code for each house that is associated with the search:

<ul>

<?php
foreach($houses as $house) {
?>

<li><?=$house->$zipcode?></li>

<?php
}
?>

</ul>

How would I modify this to print out only 1 occurrence of each zip code that is in the search? For example, what if there are 60 houses in the search but all the homes come from a total of 3 zip codes? How would I be able to just pull these three zips from the search?

Thanks in advance!

penders

11:11 pm on Sep 7, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You'll need to keep track of the zip codes you output and not output a zip code if it already appears in the list (array) you'll be using....

<?php 
$zipCodes = array(); // Array to store all the unique zipcodes we output
foreach($houses as $house) {
// Is this zipcode already in the array? If so, skip it
if (isset($zipCodes[$house->zipcode])) {continue;}
?>
<li><?=$house->zipcode?></li>
<?php
// Record this zipcode in the array
$zipCodes[$house->zipcode] = true;
}
?>


Note... I've removed the '$' before zipcode - I assume that was a typo?

tec4

1:44 am on Sep 8, 2011 (gmt 0)

10+ Year Member



Worked like a charm :)

Thank you very much for the help. It makes sense, just got to get used to the logic of it..still getting warmed up to all of it.

And yes, the "$" was a typo - good catch.

Thanks for the help Penders!