PHP return data from loop in function

The idea behind writing a post to return data from loop in function in PHP just came into my mind because a fresher was trying to set up a function to return data from loop and hoping it would then run a return each time within the loop and the function would echo each out one by one. See the code below:

Actually you can’t achieve the same using that approach at all so I decided to write an article to explain how this would be achieved?

The mistake is return returns only the record fetched in first run of loop and stops function from executing further.

So the correct way is either save the result created in loop to a variable or an array and return the variable/array to calling code.

We have used .(dot) as string concentration operator while using variable to return loop data by function.

Now modify your calling code in this way if you used array:

Array would be better if you want to process something with result or getting an array returned can be more useful in the future.

That is the correct way to return data from loop in function in PHP.

You Might Interested In