问题
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