为数组元素设置PHP,而变量不是数组 [英] PHP isset for an array element while variable is not an array

查看:82
本文介绍了为数组元素设置PHP,而变量不是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

此代码返回1.为什么?

This code returns 1. Why?

推荐答案

字符串字符的偏移量可以使用第一个字符的语法,例如$ a [0]来引用,例如

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'

因此PHP意识到$ a是一个字符串;将'b'强制转换为数字(强制转换为0),然后尝试测试$ a [0]上的isset,这是第一个字符a

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

如果您启用了错误,它也会抛出非法的偏移'b'警告

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

编辑

$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

这篇关于为数组元素设置PHP,而变量不是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆