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?
Strings are similar to arrays with just a few differences. Usually, the array size is fixed, while strings can have a variable number of elements. Arrays can contain any data type (char short int even other arrays) while strings are usually ASCII characters terminated with a NULL (0) character.
A string is an array if you treat it as an array, eg: echo $text[0] , but print_r Prints human-readable information about a variable, so it will output that variable. So your answer is, string is an array.
Arrays can have keys as well and can be sorted. If strings were full arrays, you could give each letter a key, or sort the letters alphabetically using one of the array functions.
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With