Reputation:
Given a PHP associative array like this one:
$a = array(
'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple'
);
I want to search a key and, if not found, I want to add 'myKey'=>0. Which is the best way to do such a thing?
Upvotes: 2
Views: 20763
Reputation: 47883
You don't need to "check" if the key exists. Just use the array union operator to attempt the appending of one or more elements to the input array.
The array union assigment operator (+=
) is shorthand for $a = $a + $newArray;
. Demo
$a = [
'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple'
];
$a += ['myKey' => 'foo']; // this is added because the key doesn't exist
$a += ['shape' => 'bar']; // this is ignored because the already key exists
$a += ['zero']; // this is added because the 0 key doesn't exist
$a += ['not zero']; // this is ignored because the 0 key already exists
var_export($a);
Output:
array (
'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
'myKey' => 'foo',
0 => 'zero',
)
Upvotes: 0
Reputation: 12244
You have 2 ways, if you are sure your keys CAN'T have NULLs, then you can use the isset()
. isset
only returns true when the key is set and its value is different than null
.
if(!isset($a['keychecked'])){
$a['keychecked'] = 0;
}
BUT, if you have NULLS in your array. You HAVE to use array_key_exists() which is longuer to write but not subjet to the isset(NULL) == false rule.
if(!array_key_exists('keychecked', $a)){
$a['keychecked'] = 0;
}
Upvotes: 8
Reputation: 44288
You can use the null coalesce operator if you don't store null
values:
$a['myKey'] ??= 0;
Note that if the key myKey
already exists with a null
value, then the above statement will override that value.
Upvotes: 2
Reputation:
You are looking for the array_key_exists
function:
if (!array_key_exists($key, $arr)) {
$arr[$key] = 0;
}
Upvotes: 25
Reputation: 521
<?php
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple');
$key = 'myKey';
if (!array_key_exists($key, $a)) {
$a[$key] = 0;
}
?>
Upvotes: 2
Reputation: 324620
if( !isset($a['myKey'])) $a['mkKey'] = 0;
Or
$a['myKey'] = $a['myKey'] ? $a['myKey'] : 0;
Or
$a['myKey'] = (int) $a['myKey']; // because null as an int is 0
Upvotes: 3