isset() returns true 来自作为具有任何键的数组访问的字符串变量

isset() returns true from a string variable accessed as an array with any key

我遇到这样的问题:

$area="Dhaka";

isset($area); //returns true which is OK

isset($area['division']); //returns true why?

// actually, any array key of area returns true

isset($area['ANY_KEY']);//this is my question 1

isset($area['division']['zilla');//now it returns false. 

//as I know it should returns false but why previous one was true.

现在如果我这样做:

$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this

isset($area['division']['ANY_KEY']); // returns true why? question #2

基本上我的两个问题都是一样的

谁能解释一下?

与现有的所有编程语言一样,字符串存储为字符数组。

如果我这样做了:

$area = "Dhaka";
echo $area[0];

会 return D.

我也可以通过以下方式回显整个字符串:

echo $area[0].$area[1].$area[2].$area[3].$area[4];

PHP will also type juggle a string into 0 以仅接受整数的方式传递时。

所以这样做:

echo $area['division'];

你基本上会做:

echo $area[0];

再一次,得到 D.

这就是为什么 isset($area['division']) return 是 true 值的原因。

为什么 $area['foo']['bar'](又名 $area[0][0])不起作用?因为$area只是一个一维数组。

当您使用可以是字符串或数组的变量时,处理此问题的最佳方法是在尝试将您的变量视为数组之前使用 is_array() 进行测试:

is_array($area) && isset($area['division'])

这是预期的行为。

PHP Documentation covers this

您可以试试 empty()。

PHP 允许您将字符串视为数组:

$foo = 'bar';
echo $foo[1]; // outputs 'a'

所以

$area['division']

将 parsed/executed 为

$area[0];

(键不能是字符串,因为它不是真正的数组,所以 PHP 通过其转换为整数的规则对 division 字符串进行类型转换,并给出 0), 求值到达卡字母D, 显然是set.

如果它为不存在的键返回 true,那么您无能为力;但是,您可以确保它不会对您的代码产生负面影响。只需使用 array_key_exists() 然后对数组元素执行 isset()。

编辑:事实上,使用 array_key_exists() 如果它行为不当,您甚至不需要 isset 只需使用类似 strlen() 的东西或检查值类型 if array_key_exists returns 正确。

重点是,不仅仅是说 isset($Ar['something']) do:

if(array_key_exists('something',$Ar) )

并在必要时检查值的长度或类型。如果您需要在此之前检查数组是否存在,当然可以仅在数组本身上使用 isset() 或 is_array()。

好的,这是一个解决方案,而不是解释为什么 isset 无法正常工作。

您想检查数组元素是否是根据它的索引字符串设置的。我可能会这样做:

function isset_by_strkey($KeyStr,$Ar)
{
    if(array_key_exists($KeyStr,$Ar))
    {
        if(strlen($Ar[$KeyStr]) > 0 || is_numeric($Ar[$KeyStr] !== FALSE)
        {
            return TRUE;
        }
        return FALSE;
    }
}

isset_by_strkey('ANY_KEY',$area); // will return false if ANY_KEY is not set in $area array and true if it is.

在php中访问线性数组的最佳方式是

// string treated as an linear array 
$string= "roni" ;
echo $string{0} . $string{1} . $string{2} . $string{3};

// output = roni