Daily Archive for April 24th, 2009

array_fill

PHP provides the array_fill function to create an array containing identical values a fixed number of times. To quote the example on the documentation page, code such as:

$a array_fill(56'banana');

Generates this kind of array:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

But the documentation does not answer an important question: are the values inserted into the array merely copies of the argument, or are they actual references to the argument?

This may not seem like much, but PHP5 introduces manipulation of objects by reference (since working by value seldom plays nicely with object mutation) so it can be interesting to know how an array of objects reacts.

The result is quite interesting. Consider the following code:

$obj = (object)array('x' => 0);
$arr array_fill(02$obj);
$arr[0]->1;

The expected output, if all the elements are independent copies, is that only the first cell will have a value of zero:

Array
(
  [0] => object(stdClass)#1 { ["x"] => 1 }
  [1] => object(stdClass)#1 { ["x"] => 0 }
)

But what really happens is that all the cells in the array actually reference the original object, which means the array will actually look like this:

Array
(
  [0] => object(stdClass)#1 { ["x"] => 1 }
  [1] => object(stdClass)#1 { ["x"] => 1 }
)

Oops! I hope you weren’t relying on that function for filling an array of objects.

On the other hand, since arrays are manipulated by value, code such as …

array_fill(0, 10, array_fill(0, 10$value));

… does indeed create a 10×10 grid of independent cells.



1150 feed subscribers
(readers who polled a feed this week)