user9117670
user9117670

Reputation: 151

foreach loop returns only one item from the array

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

Upvotes: 0

Views: 4526

Answers (2)

ArtOsi
ArtOsi

Reputation: 943

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

Upvotes: 1

Ethan
Ethan

Reputation: 4375

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

Upvotes: 2

Related Questions