0

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); 
3
  • 6
    what do you expect when you use return ? Commented Dec 19, 2017 at 11:06
  • As you are using return, compiler will take you out of the function in the first iteration. Commented Dec 19, 2017 at 11:08
  • 5 <p> tags but it only shows the first one Commented Dec 19, 2017 at 11:09

2 Answers 2

2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

David already gave you an answer, so you can accept his and close question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.