foreach loop returns only one item from the array

眉间皱痕 提交于 2021-02-17 07:12:25

问题


I have an array that I loop through with for each loop it returns only the first iteration but if I change it to echo it prints all of them to the screen, new to PHP not sure why is it acting this way tried looking for an answer but did not find one. the code below:

    function getData($values){
        foreach ($values as $key => $value){
            return "<p>". $key . " " . $value ."</p></br>";

        }

    }

    $SubmitedResult->SerialisedForm = getData($data);

回答1:


return always exits the function and returns its argument. From the docs:

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

If you don't want this to happen, try appending to a variable, and returning it when you've finished appending:

function getData ($values) {
    $form = '';
    foreach ($values as $key => $value) {
        $form .= "<p>". $key . " " . $value ."</p></br>";
    }
    return $form;
}



回答2:


return after loop iterates.

function getData($values){
        $tags = [];
        foreach ($values as $key => $value){
            $tags[] =  "<p>". $key . " " . $value ."</p></br>";
       }

       return $tags;
}

    $SubmitedResult->SerialisedForm = getData($data);


来源:https://stackoverflow.com/questions/47885585/foreach-loop-returns-only-one-item-from-the-array

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