user3210543
user3210543

Reputation:

Displaying only unique values from array PHP

First I check if the current value is part of the array of already displayed values. If it's not, I display it. I still get duplicate values and I don't know why.. Here's my code:

while ($row = mysql_fetch_array($result))
{
    $displayed = array();
    if (!(in_array($row['Brand'],$displayed)))
    {
        array_push($displayed,$row['Brand']);
        echo '<li>';
        echo $row['Brand'];
        echo '</li>';
    }
}

Upvotes: 0

Views: 321

Answers (4)

Alireza Fallah
Alireza Fallah

Reputation: 4607

Use array_unique($array) to remove every repeated value easily .

Refrence

Upvotes: 1

mpgn
mpgn

Reputation: 7251

You can try this code :

$displayed = array(); //move here 
while ($row = mysql_fetch_array($result))
{
    if (!(in_array($row['Brand'],$displayed)))
    {
        array_push($displayed,$row['Brand']);
        echo '<li>';
        echo $row['Brand'];
        echo '</li>';
    }
}

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76656

You are re-initializing the array on each iteration, so you are effectively checking if $row['Brand'] exists in an empty array. It doesn't and hence in_array returns false. Move the array declaration outside the loop.

$displayed = array();
while ($row = mysql_fetch_array($result))
{
    # code ...
}

Usual disclaimer: mysql_* functions are deprecated and are soon to be removed. Please switch to MySQLi or PDO instead.

Upvotes: 0

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

You are reinitializing $displayed = array(); on every iteration of the while loop and essentially clearing any data in it. Move it outside, before the loop.

Upvotes: 4

Related Questions