Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 557
hairynuggets Avatar asked Feb 21 '12 11:02

hairynuggets


2 Answers

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'];
}
like image 95
hsz Avatar answered Nov 05 '22 22:11

hsz


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.

like image 27
ale Avatar answered Nov 05 '22 23:11

ale