Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When defined variable can be accessed inside of multidimensional array?

I'm very surprised that PHP behaves so weirdly. When building a multidimensional array, it seems that you can't access child array's variable, before the last ); is closed.

Example:

$config['debug']             = array(
        'type'                 => array(
            'remote_specific'    => true,
            'remote_addr'        => '1.2.3.4',
        ),
        'mode'               => array(
            'PHP'              => ($config['debug']['type']['remote_specific'] && $config['debug']['type']['remote_addr'] == $_SERVER['REMOTE_ADDR']) ? true : true,
            'PDO'              => ($config['debug']['type']['remote_specific'] && $config['debug']['type']['remote_addr'] == $_SERVER['REMOTE_ADDR']) ? true : false
        )
     );

You would simply get an error: PHP Notice: Undefined variable: config in ..

Online example

It seems that PHP is writing it to the memory after closing parent array's );.

What am I missing here?

like image 486
Ilia Avatar asked Dec 06 '25 14:12

Ilia


2 Answers

In most languages, an assignment (A = B) is actually a two-step process: first the entire right-hand operand (B in the example) is evaluated, and then the result of that evaluation is assigned to the left-hand operand (A). Within the evaluation of B, the assignment to A hasn't happened yet; it does not occur continuously while B is being evaluated, but as a single atomic operation after B has been completely evaluated.

like image 117
lanzz Avatar answered Dec 08 '25 04:12

lanzz


That's like trying to read a book before taking it off the shelf. In PHP, you can't access an array elements before it's defined.

The array only gets defined after the full statement is evaluated, so when you try to access $config['debug']['type']['remote_specific'] inside the array, $config is an unknown variable to PHP, and hence a Notice is thrown.

like image 38
Amal Murali Avatar answered Dec 08 '25 02:12

Amal Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!