Using foreach with SplFixedArray

强颜欢笑 提交于 2019-12-04 06:23:49

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/22942860/using-foreach-with-splfixedarray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!