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)
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).