17

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ritesh
  • 4,720
  • 6
  • 27
  • 41
  • 2
    You can bypass this behaviour with `(is_array($host) && isset($host["name"]))`. Always check against the type you need if it's not clear which type you'll received. For more details on the behaviour you described see Rizier123s answer. – TobiasJ Sep 14 '15 at 10:53
  • If you are interested in some of the other things that can catch you off-guard in PHP, read this. http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ – Almo Sep 14 '15 at 17:13
  • 1
    Why do strings behave like an array...? Because they are an array... – SnakeDoc Sep 14 '15 at 18:40

1 Answers1

23

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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156