How does this task work?

I don’t know if something like this has been asked. Can someone explain how this task works in the following cases:

$a = "1"; $a[$a] = "2"; echo $a; 

This gives the result: 12

 $a = "1"; $a[$a] = 2; echo $a; 

This gives the result: 12

 $a = 1; $a[$a] = 2; echo $a; 

This gives the result: E_WARNING: type 2 - You cannot use a scalar value as an array - on line 6 1

+6
source share
3 answers

You create a line in the first and second cases:

 $a = "1"; //string with "1" character on index 0 $a[$a] = "2"; //on second index you put "2". The equivalent of the following: $a[1]="2" $a{1}="2" $a[1]=2 $a{1}=2; 

Since you use it as a string, 2 used as a string, so cases 1 and 2 give the same result.

Similarly, in the first case, when you use the string "1" as an index, it is converted to an integer in $a[$a] .

In the latter case, $a is an integer, you cannot add characters to the next position, as in the string

+1
source

The first two examples you provided use strings. Strings can be processed as an array, and characters are available by their integer positions.

In the third example, you assign $a as an integer that has no character references for the reference.

+5
source

The following data structures support the disordering of arrays:

(*) Lines do not support the [] operator.

Other data types (such as integers ) do not support it, and since both strings and arrays support the [n] operator, it cannot be forced to another type.

In your examples:

 $a = "1"; $a[$a] = "2"; 

It is equivalent to:

 $a = "1"; $a[(int)"1"] = "2"; // or $a[1] = "2"; 
+2
source

Source: https://habr.com/ru/post/989786/


All Articles