Sp0T
Sp0T

Reputation: 284

How does this assignment work?

I don't know whether something similar has been asked.Can someone explain how the assignment works in the following cases:

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

This gives output : 12

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

This gives output : 12

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

This gives output: E_WARNING : type 2 -- Cannot use a scalar value as an array -- at line 6 1

Upvotes: 6

Views: 67

Answers (3)

n-dru
n-dru

Reputation: 9430

You are building a string in first and second case:

$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;

As you use it as a string, 2 is cast as string, that's why case 1 and 2 give the same result.

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

In last case $a is integer, you cannot add characters onto next position as in string

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173612

The following data structures support array dereferencing:

(*) Strings don't support the [] operator, though.

The other data types (such as integers) don't support it, and because both strings and arrays support the [n] operator, it can't be coerced into another type.

In your examples:

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

Is equivalent to:

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

Upvotes: 2

mproffitt
mproffitt

Reputation: 2527

The first two examples you have provided are using strings. Strings can be treated as an array and characters accessed by their integer positions.

In the third example, you're assigning $a as an integer which has no character positions to reference.

Upvotes: 5

Related Questions