add to array if it isn't there already

How do I add elements to an array only if they aren't in there already? I have the following:

$a=array();
// organize the array
foreach($array as $k=>$v){
    foreach($v as $key=>$value){
        if($key=='key'){
        $a[]=$value;
        }
    }
}

print_r($a);

// Output

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6

)

Instead, I want $a to consist of the unique values. (I know I can use array_unique to get the desired results but I just want to know)


Solution 1:

You should use the PHP function in_array (see http://php.net/manual/en/function.in-array.php).

if (!in_array($value, $array))
{
    $array[] = $value; 
}

This is what the documentation says about in_array:

Returns TRUE if needle is found in the array, FALSE otherwise.

Solution 2:

You'd have to check each value against in_array:

$a=array();
// organize the array by cusip
foreach($array as $k=>$v){
    foreach($v as $key=>$value){
        if(!in_array($value, $a)){
        $a[]=$value;
        }
    }
}

Solution 3:

Since you seem to only have scalar values an PHP’s array is rather a hash map, you could use the value as key to avoid duplicates and associate the $k keys to them to be able to get the original values:

$keys = array();
foreach ($array as $k => $v){
    if (isset($v['key'])) {
        $keys[$value] = $k;
    }
}

Then you just need to iterate it to get the original values:

$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key]['key'];
}

This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).

Using in_array instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array is in O(n)) that is not applicable. Even pushing all values in the array and using array_unique on it would be better than in_array (array_unique sorts the values in O(n·log n) and then removes successive duplicates).

Solution 4:

if (!in_array(...))  
  array_push(..)