"Indirect modification of overloaded element of SplFixedArray has no effect"

Desmond Hume picture Desmond Hume · Nov 18, 2013 · Viewed 30k times · Source

Why the following

$a = new SplFixedArray(5);
$a[0] = array(1, 2, 3);
$a[0][0] = 12345; // here
var_dump($a);

produces

Notice: Indirect modification of overloaded element of SplFixedArray has no effect in <file> on line <indicated>

Is it a bug? How do you deal with multidimensional SplFixedArrays then? Any workarounds?

Answer

hek2mgl picture hek2mgl · Nov 18, 2013

First, the problem is related to all classes which implement ArrayAccess it is not a special problem of SplFixedArray only.


When you accessing elements from SplFixedArray using the [] operator it behaves not exactly like an array. Internally it's offsetGet() method is called, and will return in your case an array - but not a reference to that array. This means all modifications you make on $a[0] will get lost unless you save it back:

Workaround:

$a = new SplFixedArray(5);
$a[0] = array(1, 2, 3); 
// get element
$element = $a[0];
// modify it
$element[0] = 12345;
// store the element again
$a[0] = $element;

var_dump($a);

Here is an example using a scalar which fails too - just to show you that it is not related to array elements only.