Returning distinct values from foreach loop in PHP?

28,313

Solution 1

Try with:

$property_types = array();
foreach($search_results_unique as $filter_result){
    if ( in_array($filter_result['property_type'], $property_types) ) {
        continue;
    }
    $property_types[] = $filter_result['property_type'];
    echo $filter_result['property_type'];
}

Solution 2

http://php.net/manual/en/function.array-unique.php

Example:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input); 
print_r($result);

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

You will need to alter it slightly to check using the property_type part of your array.

Share:
28,313
hairynuggets
Author by

hairynuggets

Web developer/entrepeneur. Codes php, likes codeigniter, css and jquery.

Updated on July 19, 2022

Comments

  • hairynuggets
    hairynuggets almost 2 years

    I have a foreach loop which echo's each of the property types in my search results. The code is as follows:

    <?php 
        foreach($search_results as $filter_result) {
            echo $filter_result['property_type'];
        } 
    ?>
    

    The above code returns:

    house house house house flat flat flat
    

    I would like to do something similar to the MySQL 'distinct', but I am not sure how to do it on a foreach statement.

    I want the above code to return:

    • house
    • flat

    Not repeat every item each time. How can I do this?

  • Wesley van Opdorp
    Wesley van Opdorp about 12 years
    I don't like this one really, besides the fact that the distinction should be done when fetching the data, you blindly add it to an array just to use array_unique on it. Thats adding another symptom fix in my opinion.
  • giorgio
    giorgio about 12 years
    second loop is unnecessary as you could just print or obsolete the current record if found/not found in the array
  • Eugen Rieck
    Eugen Rieck about 12 years
    @WesleyvanOpdorp You trade RAM for CPU: The array_unique() version is much faster, but needs more RAM, but the in_array() version is much slower, while using less RAM. In the OQ there were only 6 rows, which makes the additional RAM of array_unique() a no brainer IMHO
  • Widor
    Widor about 12 years
    True - although this would be handy if you wanted to preserve the array for later use rather than only printing to screen as you go.
  • giorgio
    giorgio about 12 years
    also true :) choose whatever is needed, although one-loop will be marginally faster
  • DustWolf
    DustWolf about 4 years
    Please note that array_unique does not behave as expected if your values are not strings or numbers.