给定一个像这样的PHP关联数组:
$a = array(
'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple'
);
我想要搜索一个键,如果找不到,我想要添加'myKey'=>0。哪种方法最好实现这个功能?
给定一个像这样的PHP关联数组:
$a = array(
'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple'
);
我想要搜索一个键,如果找不到,我想要添加'myKey'=>0。哪种方法最好实现这个功能?
如果你确定你的键不可能为空,那么你有两种方法可以选择,一种是使用ISSET()函数。
if(!isset($a['keychecked'])){
$a['keychecked'] = 0;
}
但是,如果你的数组中有NULL值,你必须使用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;
}
?>
E_NOTICE
错误,如果可以避免最好不要这样做。 - user142162error_reporting
没有将它们排除在外,它会抛出E_NOTICE
。 - Niet the Dark AbsolmyKey
被设置为空字符串之类的值,可能会出现问题...看起来第一个选项是最好的,除非你特别清楚可能出现的情况。 - Niet the Dark Absol