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:

<?php echo getNewsData(); ?>
<?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.

<!-- 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:

<!-- 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.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.