2

I'm trying to return a list of course id's from my database with PDO. I can access the data, however, I only want to return an array of unique id's i.e.

This

1,2,2,3,4,4

Becomes

1,2,3,4

I'm using the code below

$sth = $dbh->prepare('SELECT courseId from training');  
    $sth->execute();  
        $row = $sth->fetchAll();
        $result = array_unique($row);
        print_r($result); 

But, it returns only 1 id:

Array ( [0] => Array ( [courseId] => 8 [0] => 8 ) )

If I print_r $row I can see all my courseId's

What am I doing wrong?

1
  • Quick tip - when executing queries that don't require data binding, just use the method query() like this: $sth = $dbh->query('SELECT courseId FROM training');. To be more efficient, you can even populate the variable with the result of the query in the same line, like this: $sth = $dbh->query('SELECT courseId FROM training')->fetchAll(PDO::FETCH_ASSOC);. Commented Mar 15, 2012 at 21:02

3 Answers 3

5

What am I doing wrong?

You are not reading the friendly manual on array_unique, where you can see this:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

Since $result contains arrays, and the string representation of each of them is the same ("Array" IIRC) then all the elements compare "equal" and only the first is left.

How to solve the problem: Several ways.

One would be to let the database do it for you with SELECT DISTINCT.

Another would be to go from an array of arrays to an array of just ids, and then array_unique will work just fine. This can be simply done with a foreach loop, or (probably better) with array_map, e.g:

$ids = array_map(function($el) { return $el['courseId']; }, $row);
$unique = array_unique($ids);
Sign up to request clarification or add additional context in comments.

Comments

4

Perhaps you would be better off by doing this query:

SELECT DISTINCT courseId FROM training

That way the data coming from the database is already unique and there is no need to use array_unique.

1 Comment

Thanks Alec. I'll use that instead. I'm just trying to figure out what I'm doing wrong with array_unique so I know for the future.
0

Its the comaprison array_unique is using. I would just do this in the query by using DISTINCT.

1 Comment

See Jon's Post above... I didnt go into more detail because after i wrote the initial part of my answer there were 2 others containing the same detail and recommendation :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.