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)
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.
Easy to write, but not the most effective one:
$array = array_unique(array_merge($array, $array_to_append));
This one is probably faster:
$array = array_merge($array, array_diff($array_to_append, $array));
if (!in_array($value, $a))
$a[]=$value;
Try adding as key instead of value:
Adding an entry
function addEntry($entry) {
$this->entries[$entry] = true;
}
Getting all entries
function getEntries() {
return array_keys($this->enties);
}
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 (!in_array(...))
array_push(..)