PHP isset for an array element while variable is not an array

不羁的心 提交于 2019-12-10 19:01:42

问题


$a = 'a';
echo isset($a['b']);

This code returns 1. Why?


回答1:


String characters can be referenced by their offset using syntax like $a[0] for the first character, e.g.

$string = 'Hello';
echo $string[1];  // echoes 'e'

so PHP is recognising that $a is a string; casting your 'b' to a numeric (which casts to a 0), and trying to test isset on $a[0], which is the first character a

Though it should also throw an illegal offset 'b' warning if you have errors enabled

EDIT

$a = 'a';
echo isset($a['b']), PHP_EOL;
echo $a['b'];

PHP 5.3

1
a

PHP 5.4

Warning: Illegal string offset 'b' in /Projects/test/a10.php on line 6
a

PHP 5.5

PHP Warning:  Illegal string offset 'b' in /Projects/test/a10.php on line 6

Warning: Illegal string offset 'b' in /Projects/test/a10.php on line 6
a



回答2:


Only for php 5.3:

so lets do it slowly:

$a['b'];

returns 'a' because b is converted to 0 and $a[0] (the first char of 0 = a)

isset($a['b']);

return true because $a['b'] is 'a' not null

echo true;

outputs "1" because true is converted to a string and this to "1".




回答3:


because ISSET return the 1 if the value is set.

Use it like this :

if(isset($a['b']){
echo $a['b'];
}



回答4:


For the same reason as this...

echo true;

PHP cannot echo a non-string/non-integer so it converts the true into 1 and 0 for false.




回答5:


<?php
$a = 'a';
var_dump($a);
?>
it will gives output string(1) "a" 
if you will echo $a['b'] it will give you output as a so $a['b'] also has value
hence
<?php
$a = 'a';
echo isset($a['b']);
?>
outputs value 1


来源:https://stackoverflow.com/questions/18399372/php-isset-for-an-array-element-while-variable-is-not-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!