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)
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.
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With