views:

18

answers:

2

Hi, I have a nasty little problem with the pointer opperator in php (&). I want to loop through a while loop, which writes data in an array. Each time it is supposed to write into the next dimension of the array (1st in $array, then in $array[0], then in array[0][0], etc). I wanted to do this by linking to $array with a pointer, then changing the pointer like this:

$pointer = &array;
while($bla){
  $pointer = &$pointer[0];
}

So everytime while is triggered the pointer links to a further dimension of $array. That doesn't seem to work though...

I would really appretiate your help, thank you.

A: 

I'm not sure if this is what you wanted, but here you are. :-)

$a = array();

$b = &$a;

for ($i = 0; $i < 6; $i++) {
    $a[0] = array();
    $a = &$a[0];
}

print_r($b);

Outputs:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => Array
                                (
                                    [0] => Array
                                        (
                                            [0] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

        )

)
Krab
A: 

I tried your code and it works. Test:

<?php
    error_reporting(E_ALL | E_STRICT);

    $array = array();
    $ptr =& $array;
    for ($i = 0; $i < 10; ++$i) {
        $ptr[0] = array();
        $ptr =& $ptr[0];
    }

    unset($ptr);
    var_dump($array);

    $ptr =& $array;
    while (!empty($ptr)){
        $ptr =& $ptr[0];
        var_dump($ptr);
    }

This first creates the array and then does the loop.

nikic
You're right. I seem to have another bug in my code. Thank you!
yajRs