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:
1 | <?php echo getNewsData(); ?> |
1 2 3 4 5 6 7 8 9 | <?php function getNewsData() { //query stuff while($row = mysql_fetch_array($result)) { $loopdata = "Looped data"; return $loopdata; } } ?> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!-- Using a variable --> <?php function getNewsData() { //query stuff $loopdata = ''; while($row = mysql_fetch_array($result)) { $loopdata .= "Looped data"; } return $loopdata; } ?> <!-- Using an array --> <?php function getNewsData() { //query stuff $loopdata = array(); while($row = mysql_fetch_array($result)) { $loopdata[] = "Looped data"; } return $loopdata; } ?> |
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:
1 2 | <!-- If using an array --> <?php echo implode("<br />\n", getNewsData()); ?> |
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.