Search code examples
phpmysqlarraysselectarray-unique

array_unique not working in PHP?


I have got a table in my MySql database:

  pageid   | text
-----------+----------
    1      | test
-----------+----------
    2      | example
-----------+----------
    3      | another
-----------+----------
    1      | example1

and this PHP code:

$query = "SELECT pageid FROM test";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
  {
  $id = $row['pageid'];
  $id1 = array($id);
  $id2 = array_unique($id1);
  foreach ($id2 as $value)
    {
    echo $value . "<br>";
    }
  }

But it returns:

1
2
3
1

I would like to make the pageids unique. So I would like to echo out the number 1, once. Like this:

1
2
3

So what am I doing wrong? How could I achieve what I want?

Thanks in advance...

[I know that this code doesn't make much sense, but this is just a demo for this question and I have a much more complicated code :) ]


Solution

  • Of course, the real answer in this situation is to select distinct records to begin with:

    $query = "SELECT DISTINCT pageid FROM test";
    

    But as to why your code doesn't work...

    You are declaring $id1 as an array, but not appending to it. Instead you're just creating a 1 element array each time. Instead, append all results then call array_unique()

    $query = "SELECT pageid FROM test";
    $result = mysql_query($query);
    
    // Declare array first
    $id1 = array();
    while($row = mysql_fetch_array($result))
      {
      $id = $row['pageid'];
      // Append to the array...
      $id1[] = $id;
      }
    
    // Call array_unique() outside the loop:
    $id2 = array_unique($id1);
    foreach ($id2 as $value)
    {
      echo $value . "<br>";
    }