在数组内分配值

can someone explain this to me:

$a = array( $b1 = "b1", $b2 = "b2", array($b3 = "b3", $b4 = "b4"));

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

Why is this legal? The output is still "b4" even echoing $a[2][1], $$a[2][1], $$$[2][1] and so on.

What I expect is it will look for a variable "b4" if echoing $a[2][1] but it's still echoing the string "b4".

Thanks

The result of assigning a value to a variable is the value itself. Therefore the above expression has side effects, but without those side effects, it could be written as:

$a = array( "b1", "b2", array("b3", "b4"));

Basically what is happening here is that you're declaring the $b* variables as you're adding them to the array. Your code above is equivalent to

Array("b1","b2", Array("b3", "b4"));

Which in turn is equivalent to

Array(0 => "b1", 1 => "b2", 2 => Array(0 => "b3", 1 => "b4"));

The second array is effectively includes the array indices which Php adds by default where an index is not defined.

When you input

Array($b1 = "b1");

the

$b1 = "b1" 

is evaluated as "b1" prior to insertion in the array.

You may just be using the wrong operator for what you are trying to do. => is used to set keys in an array.

The = works for the same reason this line works:

if ($b1 = 'foo') {
    echo $b1; // prints foo
}

The assignment operator (=) returns the value.

$a = array( $b1 = "b1", $b2 = "b2", array($b3 = "b3", $b4 = "b4"));

In your array, you are not setting any keys. You are setting values to the variables $b1, $b2, $b3, and $b4 and then using those values in a (numeric) array.

So, $b4 = "b4". This sets $b4 to the string "b4", and then adds it to the array.

$a[2][1] is the string "b4", so $$a[2][1] is the value of $b4 which is "b4", which makes $$$a[2][1] also "b4", and so on.

There's nothing confusing about this. Inside the array you have $b4 = "b4". Double dollar means, get the string and access the variable by that name, which is again "b4"