$arr = array(array(array()));
foreach($arr as $subarr)
{
$subarr[] = 1;
}
var_dump($arr);
Output:
array(1) {
[0]=>
array(1) {
[0]=>
array(0) {
}
}
}
But for object,it’s reference:
class testclass {
}
$arr = array(new testclass());
foreach($arr as $subarr)
{
$subarr->new = 1;
}
var_dump($arr);
Output:
array(1) {
[0]=>
object(testclass)#1 (1) {
["new"]=>
int(1)
}
}
Why treat array different from object?
PHP passes all objects by reference. (PHP5?)
PHP passes all arrays by value.
Originally PHP passed both objects and arrays by value, but in order to cut down on the number of objects created, they switch objects to automatically pass by reference.
There is not really a logical reason why PHP does not pass arrays by reference, but that is just how the language works. If you need to it is possible to iterate over arrays by value but you have to declare the value explicitly by-reference:
Thanks to Yacoby for the example.
Frankly I prefer arrays to be passed by value because arrays are a type of basic data structure, while objects are more sophisticated data structures. The current system makes sense, at least to me.