Desmond Hume
Desmond Hume

Reputation: 8617

Using foreach with SplFixedArray

It seems like I can't iterate by reference over values in an SplFixedArray:

$spl = new SplFixedArray(10);
foreach ($spl as &$value)
{
    $value = "string";
}
var_dump($spl);

Outputs:

Fatal error: Uncaught exception 'RuntimeException' with message 'An iterator cannot be used with foreach by reference'

Any workaround?

Upvotes: 0

Views: 1873

Answers (2)

salathe
salathe

Reputation: 51950

Any workaround?

Short answer: don't iterate-by-reference. This is an exception thrown by almost all of PHP's iterators (there are very few exceptions to this exception); it isn't anything special for SplFixedArray.

If you wish to re-assign values in a foreach loop, you can use the key just like with a normal array. I wouldn't call it a workaround though, as it is the proper and expected method.


Original: bad

$spl = new SplFixedArray(10);
foreach ($spl as &$value)
{
    $value = "string";
}
var_dump($spl);

Assign by key: good

$spl = new SplFixedArray(10);
foreach ($spl as $key => $value)
{
    $spl[$key] = "string";
}
var_dump($spl);

Upvotes: 6

Nicholas Summers
Nicholas Summers

Reputation: 4756

According to the docs, the only advantage of splfixedarray() is that it is faster than a normal array. But I don't remember anyone referring to an array as slow. So your best solution is probably to switch to a regular array.

Upvotes: 0

Related Questions