PHP - CodeIgniter - Invalid argument supplied for foreach()
Solution 1
The variable you supply to the foreach loop has to be an array. You can skip the foreach if the value of the variable supplied is not an array with the solution below.
<?php if(is_array($result)): ?>
<?php foreach($result as $row):?>
<h3><? echo $row->title; ?></h3>
<p><? echo $row->text; ?></p>
<?php endforeach;?>
<?php endif; ?>
Solution 2
Try foreach($result->result() as $row)
- it could be you're trying to iterate through the object returned by Codeigniter's active record.
Solution 3
If you are wondering what could be in the variable, output it!
var_dump($result);
That will instantly tell you what is going on. My guess, you have returned FALSE somewhere from your model, or you are using the DB object and not result() or result_array() (as suggested by Alex).
Solution 4
You can use the empty php function and do something like
<?
if(!empty($results)){
echo "
foreach($result as $row){
<h3>".$row->title."</h3>
<p>".$row->text".</p>
";
}
}else{
echo "<p>no results<p/>";
}
?>
Solution 5
$result is not array.
Try to check it with is_array
before foreach
.
And debug why $result is not array :P
Dzung Nguyen
Dzung Nguyen Xuan Quang CEO at https://open-consulting.co Github: https://github.com/rhacker Blog: http://rhacker.github.com LinkedIn: http://dk.linkedin.com/in/nxqdlinkedin Stay in touch: [email protected]
Updated on January 18, 2020Comments
-
Dzung Nguyen over 4 years
I try to write a site with CodeIgniter but I've a problem with PHP. I'm sure that it's so simple and can't be wrong. But I don't know bugs from , just a newbie of CodeIgniter :)
<html> <head> <title><?=$page_title?></title> </head> <body> <?php foreach($result as $row):?> <h3><? echo $row->title; ?></h3> <p><? echo $row->text; ?></p> <?php endforeach;?> </body> </html>
I've a bug from this file :
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/helloworld_view.php
Line Number: 6
thanks in advance for reading this :)
-
Phil Sturgeon about 14 yearsThis will stop the error but it will not help him work out what is going on. Alex Lawford has made the best guess here, either he is trying to use the database object or he has FALSE from his model somewhere.