lisovaccaro
lisovaccaro

Reputation: 33956

Add to array only if there isn't a key with the same value?

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.

Upvotes: 0

Views: 142

Answers (4)

Elisha Senoo
Elisha Senoo

Reputation: 3594

Use a simple construct like this:

if(! in_array($variable, $insertar["Atributos"])){
    array_push($variable,$insertar["Atributos"]);
}

Upvotes: 0

mario
mario

Reputation: 145482

Alternative cleanup and post-processing approach:

$insertar = array_map("array_unique", $insertar);

See array_unique(). Implicitly orders the value entries however.

Upvotes: 0

Nonym
Nonym

Reputation: 6299

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;
}

Upvotes: 1

Milo LaMar
Milo LaMar

Reputation: 2256

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.

Upvotes: 1

Related Questions