Let’s look at a simple piece of code:


      
$str = 'php';
$str['name'] = array('dogstart');
var_dump($str);
Copy the code

If you think about it, what does the above code output? If you already have the answer, you can close the post, otherwise let’s go through the output step by step.

Based on review of

Before we start, let’s think about the types of variables that exist in PHP:

  • Boolean Indicates the Boolean type
  • The Integer Integer
  • Float Float
  • String String
  • Array an Array
  • Object
  • Resource Resource type
  • NULL
  • The type is Callback/Callable

Reference documentation: PHP type

In PHP, a string is implemented as an array of bytes plus an integer indicating the length of the buffer (note that PHP cannot change the length of the string).

Let’s move on to our topic. The first line of code is normal. The key part is in the second line:

$str['name'] = array('dogstart');
Copy the code

Since strings in PHP are made up of arrays, we know that the key of an array in PHP can be either an INTEGER or a string, but in a string, we can only access each character using the integer subscript, so the ‘name’ at this point will eventually be converted to a number:

intval('name');
Copy the code

As defined in the PHP documentation, when a string is converted to a number, the beginning of the string determines the converted value. If the string starts with a valid value, that value is used, otherwise 0.

So the final result of the above code is 0. Using the mathematical substitution method, the second line of code becomes:

$str[0] = array('dogstar');
Copy the code

Let’s look at the code on the right of the second line. Since only strings can exist in strings, the code on the right is converted to a string:

strval(array('dogstar'));
Copy the code

When the result is ‘Array’, the second line of code becomes:

$str[0] = 'Array';
Copy the code

Since the length of the string is fixed, only one character can be placed in this space, so assignment of ‘Array’ characters to $STR [0] will keep only the first character and discard the rest. So our code becomes:

<? php$str = 'php';
$str[0] = 'A';
var_dump($str);
Copy the code

At this point you can see at a glance that the final output is ‘Ahp’.