Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of data similar to the following:

$array[0] = array('key1' => 'value1a','key2' => 'value2a','key3' => 'value3a');
$array[1] = array('key1' => 'value1a','key2' => 'value2b','key3' => 'value3b');
$array[2] = array('key1' => 'value1b','key2' => 'value2b','key3' => 'value3c');
$array[3] = array('key1' => 'value1c','key2' => 'value2c','key3' => 'value3c');

I need to use this data to create a set of dropdown lists based on each key. However, I want to remove the duplicates, so that each dropdown list only shows the unique values.

I started with:

<select>
<?php   
    foreach($array AS $arr)
        {
            print "<option>".$arr['key1']."</option>";
        };
?>
</select></br>

as expected, this gave me 4 entries, two of which were the same.

So I tried:

<select>
<?php   
    foreach(array_unique($array) AS $arr)
        {
            print "<option>".$arr['key1']."</option>";
        };
?>
</select></br>

and also:

<select>
    <?php   
        $arr = array_unique($array);
        foreach ($arr AS $a)
            {
                print "<option>".$a['key1']."</option>";
            };
    ?>
</select></br>  

But these only give me one item (value1a). On closer inspection I see that it has actually generated a string of errors:

Notice:  Array to string conversion in C:\Apache24\htdocs\TEST\test29.php on line 39

But I can't figure out why this is, or how to fix it to get the list I want?

How can I get a list of just the unique entries?

share|improve this question
1  
$array is multidimensional array. Do print_r($array); and you will see what I am talking about. –  Glavić Sep 4 '13 at 8:12
1  
This example could help you . stackoverflow.com/questions/3598298/… –  Piyush Aggarwal Sep 4 '13 at 8:42
add comment

1 Answer

up vote 3 down vote accepted

Since PHP 5.5, you can use array_column function:

    foreach(array_unique(array_column($array, 'key1')) AS $arr)
    {
        print "<option>".$arr."</option>";
    };

but, it you have older version, you can do:

    foreach(array_unique(array_map(function($rgItem)
    {
       return $rgItem['key1'];
    }, $array)) AS $arr)
    {
        print "<option>".$arr."</option>";
    };
share|improve this answer
 
cheers for that, I'm currently running PHP 5.4, but the second option you gave seems to work a treat. –  IGGt Sep 4 '13 at 11:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.