1

I am using array_unique to get rid of the duplicate values in an array. But, the problem is array_unique does not consider data types while checking for duplicates. For example:

$a = [1, true, null, false];
$u = array_unique($a);
var_dump($u);

Outputs:

array(2) {
  [0] =>int(1)
  [2] =>NULL
}

But, if you consider data types every value of the array are unique. I know I can fix this by running a loop. But, is there a better way or an alternative to array_unique by which I can achieve this?

2
  • you will have to custom loop Commented Sep 28, 2016 at 23:59
  • From the documentation: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. It's intended for strings and numbers, not arbitrary types. Commented Sep 29, 2016 at 0:06

2 Answers 2

1

I came up with this solution that seems to work:

<?php
function array_really_unique($array){
    foreach ($array as $key => $item){
        foreach ($array as $key2 => $item2)
            if ($key2 != $key && $item2 === $item)
                unset($array[$key]);
    }
    return $array;
}

$a = [1, true, null, false, false, false, true, null, 2, 3, "hi", 2];
$u = array_really_unique($a);
var_dump($u);
?>

Result:

array(7) { [0]=> int(1) [5]=> bool(false) [6]=> bool(true) [7]=> NULL [9]=> int(3) [10]=> string(2) "hi" [11]=> int(2) }

It's not so elegant and is probably not that fast, but seems to work.

It will keep only the last value in the array.

Working example: example

Sign up to request clarification or add additional context in comments.

Comments

1

i was bored :)

$a = ['test',1, true, null, false,null,'test',true];

function arrayUnique($a)
{
    $u=array();
    foreach ($a as $k => $v) {
        if(!in_array($v,$u,TRUE)){
          $u[]=$v;  
        }

    }
        return $u;
}

var_dump(arrayUnique($a));

Output:

array(5) { [0]=> string(4) "test" [1]=> int(1) [2]=> bool(true) [3]=> NULL [4]=> bool(false) } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.