Why do strings behave like an array in PHP 5.3?

谁说我不能喝 提交于 2019-11-27 23:14:52

问题


I have this code:

$tierHosts['host'] = isset($host['name']) ? $host['name'] : $host;

It's working fine in PHP 5.5, but in PHP 5.3 the condition returns true while $host contains a string like pjba01. It returns the first letter of $tierHosts['host'], that is, p.

What's so wrong with my code?


回答1:


You can access strings like an array and prior PHP 5.4 offsets like your name were silently casted to 0, means you accessed the first character of that string:

character | p | j | b | a | 0 | 1 |
-----------------------------------
index     | 0 | 1 | 2 | 3 | 4 | 5 |

After 5.3 such offsets will throw a notice, as you can also read in the manual:

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.



来源:https://stackoverflow.com/questions/32562436/why-do-strings-behave-like-an-array-in-php-5-3

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