简体   繁体   中英

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?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM