I am using the following loop to add items to an an array of mine called $liste. I would like to know if it is possible somehow not to add $value to the $liste array if the
maybe you want to use it as an associative array instead. it's implemented as (something like) a hash table, so you get constant insert time instead of linear.
function find_uniq( $something ) {
foreach($something as $value){
$liste[$value]++;
}
return array_keys( $liste );
}
You can simply check this condition before calling array_push()
. Use array_search()
and use a strong comparison to false
to see if the value is present:
foreach( $something as $value ){
if( array_search( $value, $liste, true ) === false ){
array_push( $liste, $value );
}
}
(By the way: Add ,true
to array_search
to use "strict checking". This will use ===
for comparisons instead of ==
)
Great answers are already present above, but if you have multiple array_push() all over your code, it would be a pain to write if(in_array()) statements every time.
Here's a solution that will shorten your code for that case: Use a separate function.
function arr_inserter($arr,$add){ //to prevent duplicate when inserting
if(!in_array($add,$arr))
array_push($arr,$add);
return $arr;
}
Then in all your array_push() needs, you can call that function above, like this:
$liste = array();
foreach($something as $value){
$liste = arr_inserter($liste, $value);
}
If $value is already present, $liste remains untouched.
If $value is not yet present, it is added to $liste.
Hope that helps.