crmepham
crmepham

Reputation: 4740

Getting invalid argument for foreach error when using an array

I can not understand why this error is occurring. From what I can see I the function I use correctly returns an array of data that exists on the database. I use a foreach() to echo out each of the data in the array but it gives me the error: Warning: Invalid argument supplied for foreach().

Here is the function:

// Retrieve posts
    function retrieve_posts(){
        // start new instance of the database connection 
        global $dbh;

        // Get all the posts
        $stmt = $dbh->prepare("SELECT * FROM jacks_barbers_reviews ORDER BY date DESC");
        $stmt->execute();

        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

                $result[] = $row;
        }

        return $result;
    }

And the (simplified) foreach loop:

<?php

        $posts = retrieve_posts();


            foreach($posts AS $index){

                echo '<div class="test-wrap">'; //contains the individual testimonials
                echo '<p>' . $index['post'] . '</p>';
                echo '<p style="float:right;font-style:normal;font-size:15px;">By ' .$index['name']. '  ' .$index['date']. '</p>';
                echo '<div style="clear:both"></div>';
                echo '</div>'; // closes test-wrap
            }


    ?>

So what is causing this error?

Thanks

Upvotes: 2

Views: 1166

Answers (1)

ducin
ducin

Reputation: 26457

I guess this might happen if you have no results. You didn't initialize the $result variable in the retrieve_posts function. Null is returned and this is not an allowed value to be iterated inside foreach loop.

Try initializing the variable: $result = array(); before the while loop.

edit: Take a look at foreach official PHP docs:

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects

If you haven't initialized it, you return a null value which is neither an object nor an array.

Upvotes: 6

Related Questions