I want to add $variable
only if there isn't a key with the same value in array $insertar["Atributos"]
.
$insertar["Atributos"][] = $variable;
I can do it using a foreach to check beforehand if $variable
is stored and insert only if it isn't but I want to know if there is an easier way.
To be clear:
I want to add $variable
only if there isn't a key with the same value in array $insertar["Atributos"]
.
# check if $variable exists as a value in $insertar["Atributos"], and not a key
if (in_array($variable, $insertar["Atributos"])) {
# add $variable as a VALUE to the array
$insertar["Atributos"][] = $variable;
}
Sorry I read the question wrong. Try if (! in_array($value, $array)) { ... }
At first I thought you meant if the value is a key. If you want to check if a key is in an array use isset($array[$key])
rather than array_key_exists
because isset will perform much faster on long arrays.
Alternative cleanup and post-processing approach:
$insertar = array_map("array_unique", $insertar);
See array_unique()
. Implicitly orders the value entries however.
Use a simple construct like this:
if(! in_array($variable, $insertar["Atributos"])){
array_push($variable,$insertar["Atributos"]);
}