簡體   English   中英

如果找不到鍵,則將鍵添加到關聯數組

[英]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;
}

你有 2 種方法,如果你確定你的鍵不能有 NULL,那么你可以使用 ISSET()

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

但是,如果您的數組中有 NULLS。 您必須使用 array_key_exists() ,它的寫入時間更長,但不是 isset(NULL) == false 規則的子集。

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值,則可以使用空合並運算符:

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

請注意,如果鍵myKey已經存在且null ,則上述語句將覆蓋該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM