Using foreach with SplFixedArray

前端 未结 2 1590
时光取名叫无心
时光取名叫无心 2021-01-29 02:02

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

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


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-29 02:20

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

提交回复
热议问题