Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do strings behave like an array in PHP 5.3?

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?

like image 902
Ritesh Avatar asked Sep 14 '15 10:09

Ritesh


People also ask

Why is string like an array?

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.

Is string an array in PHP?

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.

How strings and arrays are related in PHP?

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.

Why do we use array in PHP?

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.


1 Answers

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.

like image 132
Rizier123 Avatar answered Nov 15 '22 14:11

Rizier123