Question

I am using PHP 5.3.5, and I am stuck with an error. I have an array

  $input = array( 
                0=>array(
                        'a'=>'one0',
                        'b'=>'two0',
                        'c'=>'three0',
                        'd'=>'four0',
                        'e'=>'five0'
                        ),
                1=>array(
                        'a'=>'one1',
                        'b'=>'two1',
                        'c'=>'three1',
                        'd'=>'four1',
                        'e'=>'five1'
                        )
            );

I use array_splice to remove the initial two values from each array by using &(value by reference) in foreach

foreach ($input as $bk => &$bv) {
         $op[]=array_splice($bv,0,2);        
}

Now when I see the $input then it adds a & just before the second array.

var_dump($input); shows this

array
  0 => 
    array
      'c' => string 'three0' (length=6)
      'd' => string 'four0' (length=5)
      'e' => string 'five0' (length=5)
  1 => & <====================================From where this `&` comes?
    array
      'c' => string 'three1' (length=6)
      'd' => string 'four1' (length=5)
      'e' => string 'five1' (length=5)

Where does & come from and how does it produce such array? Is it valid?

If I remove & in the foreach, it does not gives me desired array. Am I doing something wrong?

Was it helpful?

Solution

It's pretty counter-intuitive but it isn't actually a bug. When you use references in a loop, you're advised to unset the reference right after the loop:

foreach ($input as $bk => &$bv) {
    $op[]=array_splice($bv,0,2);        
}
unset($bv);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top