Jump to content

foreach help


tec-4

Recommended Posts

Hi All,

 

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 property that is associated with the search:

 

<ul>

 

<?php

foreach($properties as $property) {

?>

 

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

 

<?php

  }

?>

 

</ul>

 

How would I modify this to print out 1 occurrence of each zip code that is in the search, even if, for example 20 properties have the same zip code?

 

Thanks in advance!

 

P.S. - Tried using an array to work with it but pretty sure my logic was incorrect when putting it together and couldn't get past the errors.  Anyways, thanks in advance for the help!

Link to comment
Share on other sites

Can you print_r() your $properties variable? Perhaps post your class that $property holds?

 

Here's a quick and dirty solution:

<?php 

$duplicates = array('world','world','ipsum','etc','world','ipsum','baz','etc','baz',
'hello','baz','world','baz','hello','foo','etc','ipsum','ipsum','baz','ipsum','world',
'hello','hello','ipsum','baz');

$echoed = array();
foreach( $duplicates as $value ) {
if( in_array($value,$echoed) )
	continue;
echo $value.' ';
$echoed[] = $value;
}

?>

Link to comment
Share on other sites

sorry, its taken me so long to get back to this - been out of town, anyways thank you all for your responses.

 

@ btherl, sorry, that was a type.  Supposed to be "$property->zipcode"

 

@xyph - don't think i can use print_r() on it since all the properties are in a database (could be wrong tho, fairly new to the game).  But essentially I have thousands of "properties" in a database where i'd like to find unique instances of values within those properties (columns in the DB), such as the zip codes.

 

@msaz87 - I'll have to look into the array_unique() function, havent used that before - I'll definitely be looking into it, thanks for the suggestion.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.