Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add to array if it isn't there already

Tags:

php

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)

like image 492
user657821 Avatar asked May 21 '11 18:05

user657821


2 Answers

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.

like image 173
Marius Schulz Avatar answered Sep 22 '22 07:09

Marius Schulz


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;         }     } } 
like image 43
onteria_ Avatar answered Sep 24 '22 07:09

onteria_