foreach loop returns only one item from the array

前端 未结 2 970
轻奢々
轻奢々 2021-01-29 06:54

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 wh

相关标签:
2条回答
  • 2021-01-29 07:10

    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);
    
    0 讨论(0)
  • 2021-01-29 07:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题