Search code examples
phploopsforeachdistinctecho

Returning distinct values from foreach loop in PHP?


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?


Solution

  • 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'];
    }