Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shouldn't PHP array recursion throw an error?

This is the test and the response I get. I think this could be problematic and should throw an error or a notice but I cannot understand why is tolerated.

<?php
    $test = array( 0 => 'test', 1=> &$test );
    var_dump( $test );

    // array(2) { [0]=> string(4) "test" [1]=> &array(2) { [0]=> string(4) "test" [1]=> &array(2) { [0]=> string(4) "test" [1]=> *RECURSION* } } }
?>
like image 759
Elzo Valugi Avatar asked Jan 14 '10 15:01

Elzo Valugi


3 Answers

It is true recursion, and *RECURSION* is not a real error message. It's not problematic, because $test is not actively recurring, and in this case var_dump is smart enough to stop before exhausting memory.

like image 136
aercolino Avatar answered Sep 21 '22 07:09

aercolino


I would guess that detecting such a loop is non-trivial, and would be immediately apparent at runtime if the behaviour was incorrect.

like image 26
PaulJWilliams Avatar answered Sep 21 '22 07:09

PaulJWilliams


Why is it problematic? PHP is smart enough to identify that an array is being recursively called.

The same happens if you print_r($GLOBALS), I see no harm in this.

like image 1
Alix Axel Avatar answered Sep 21 '22 07:09

Alix Axel