我有一个数组
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
if($key == 'lastKey') {
echo "last found";
}
}
上面的代码不起作用。我在数组中添加了关联元素。会不会是这个原因?
我有一个数组
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
if($key == 'lastKey') {
echo "last found";
}
}
上面的代码不起作用。我在数组中添加了关联元素。会不会是这个原因?
更改==
为===
:
if($key == 'lastKey')
您现有的代码回显last found
两次,一次为 key 0
,一次为 key lastKey
。
比较整数0
和字符串'lastKey'
使用==
返回真!
字符串转换为数字
在数字上下文中评估字符串时,结果值和类型确定如下。
如果字符串包含任何字符“.”、“e”或“E”,则该字符串将被评估为浮点数。否则,它将被评估为整数。
该值由字符串的初始部分给出。如果字符串以有效的数字数据开头,这将是使用的值。否则,该值将为 0(零)。有效的数字数据是一个可选的符号,后跟一个或多个数字(可选地包含一个小数点),后跟一个可选的指数。指数是“e”或“E”后跟一位或多位数字。
用来===
比较。因为当 key0
与 string 进行比较时lastKey
, string 将被转换为 integer 并返回 false 结果。
http://codepad.org/5QYIeL4f
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
if($key === 'lastKey') {
echo "last found";
}
}
阅读有关差异的更多信息:http: //php.net/manual/en/language.operators.comparison.php
您还需要更改相等条件以检查类型。
if($key === 'lastKey')
这是因为 PHP 评估' ' == 0
为真。
当我运行你的代码时,'last found' 被输出了两次。'lastKey' 在 PHP 中被评估为 0,因此if($key == 'lastKey')
实际上匹配两次:一次用于 0,一次用于特殊元素。
使用 end() 函数获取数组的最后一个键并在 if 语句中进行比较。
$arrTest = array('val1','val2','val3','val4');
$lastKey = end($arrTest);
foreach($arrTest as $key => $val) {
if($val == $lastKey) {
echo "last found";
}
}
您的代码运行良好:在这里查看: http: //codepad.org/hfOFHMnc
但是使用 "===" 而不是 "==" 因为在将字符串与 0 进行比较时可能会遇到错误,并且它会回显两次。
<?php
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
print_r($arrTest);
foreach($arrTest as $key => $val) {
if($key == 'lastKey') { // use === here
echo "key = $key :: last found \n";
}
}
如果要测试数组键是否存在,只需使用array_key_exists
:
array_key_exists('lastKey', $arrTest)
您也可以使用isset
,但请注意,如果与键关联的值为null
.