如果找不到关键字,则将关键字添加到关联数组中


add key to associative array if key is not found

给定这样一个PHP关联数组:

$a = array(
    'color' => 'red',
    'taste' => 'sweet',
    'shape' => 'round',
    'name'  => 'apple'
);

我想搜索一个密钥,如果找不到,我想添加"myKey"=>0。做这样的事,哪种方法最好?

您正在寻找array_key_exists函数:

if (!array_key_exists($key, $arr)) {
    $arr[$key] = 0;
}

你有两种方法,如果你确定你的钥匙不能有核,那么你可以使用ISSET()

if(!isset($a['keychecked'])){
    $a['keychecked'] = 0;
}

但是,如果你的数组中有NULLS。您必须使用array_key_exists(),这是写入isset(NULL)==false规则的较长时间,但不是子jet。

if(!array_key_exists('keychecked', $a)){
    $a['keychecked'] = 0;
}
if( !isset($a['myKey'])) $a['mkKey'] = 0;

$a['myKey'] = $a['myKey'] ? $a['myKey'] : 0;

$a['myKey'] = (int) $a['myKey']; // because null as an int is 0
<?php
$a = array( 'color' => 'red',
        'taste' => 'sweet',
        'shape' => 'round',
        'name'  => 'apple');
$key = 'myKey';
if (!array_key_exists($key, $a)) {
    $a[$key] = 0;
}
?>

如果不存储null值,则可以使用null联合运算符:

$a['myKey'] ??= 0;

请注意,如果密钥myKey已经存在,并且具有null值,则上述语句将覆盖该值。