Claudio
Claudio

Reputation: 23

Remove duplicate values from Array

I can not "remove" the double values ​​from an array even if I use the function array_unique!

<?php
    $tags_array = array() ; 
    $query_tags = $mysql->Query("SELECT words AS kw FROM users ") ;
    /****
    *
    * This query return something like Array([1] => PHP,ASP,NET [2] => Ruby,Jquery,php,asp_net [3] => Php,asp,visualbasic,c# [4] => [5] =>)
    *
    *****/
    while($fetch_tags = $mysql->Fetch($query_tags)) 
    {
        foreach(explode(',',$fetch_tags['kw']) as $kw => $value) 
        {
            if(empty($value)) ;
            else 
            {
                $value = ucwords(strtolower($value)) ;
                $tags_array[] = $value ;
            } 
        }
    }
$tags_array = array_values(array_unique($tags_array, SORT_STRING)) ; 
print_r($tags_array) ;
/******
*
* print_r show somethings like this Array([1] => Asp [2] => Php [3] => Php [4] => Ruby [5] => Jquery [6] => Php [7] => Asp_net [8] = >C# [9] => Asp) 
*
* IT'S ONLY AN EXAMPLE TO SHOW YOU THE SITUATION 
*****/
?>

Upvotes: 1

Views: 1045

Answers (4)

Felix Kling
Felix Kling

Reputation: 816404

As no one seemed to have provided the right answer, I'll repeat my comment here:

It might be that the words have preceding or trailing white spaces. Then they will never be equal to each other. You can remove these white spaces with trim [docs]

$value = ucwords(strtolower(trim($value)));

Upvotes: 0

Jim
Jim

Reputation: 22656

Make sure that the returned values are in fact not unique. For example

$foo = array("PHP","php","pHP","PHP ");
$foo = array_unique($foo);

Will still contain 4 entries.

If any entries contain spaces you should trim these.

Upvotes: 1

symcbean
symcbean

Reputation: 48357

Given that is the only thing that aray_unique is supposed to do, I find it very surprising it's not doing it. What is apparent from your post, is that maybe you think 'php' is the same thing as 'PHP'?

When I try the following I get unique results:

$d=Array('PHP,ASP,NET','Ruby,Jquery,php,asp_net','Php,asp,visualbasic,c#');

$o=array();

foreach ($d as $i) {
    $p=explode(',',$i);
    foreach ($p as $q) {
      $o[]=strtoupper($q);
    }
}
print_r(array_unique($o));

However the issue only arises because your database schema is not normalised.

Upvotes: 0

hakre
hakre

Reputation: 197732

Just use values as keys, they can only exist once and you don't have any numbers as your keywords (hopefully):

$tags_array = array_keys(array_flip(($tags_array));

array_flip will use values as keys (and drop duplicate values) and array_keys will then return all keys as values again.

Upvotes: 0

Related Questions