PDOStatement and foreach loops


I’m just getting started with PHP, and am reading that I can use foreach loops to go through a result set. So for example:

foreach ($result as $row)
  $jokes[] = $row['joketext'];

…and then I can use another for each loop to access the arrays element in my HTML. For example:

<?php foreach ($jokes as $joke): ?>
<p><?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
?> </p>
    <?php endforeach; ?>

If “PDOStatement objects are designed to behave just like arrays when you pass them to a foreach loop”, why cannot I not simply do something like this:

foreach ($result as $row)
  echo "$row <br />";

Just curious!!

Thanks to all in advance.

The array based on your example code would be multidimensional so $row would output “Array” as it would contain it’s own indexes the same way MySQL and MySQLi would as well, it wouldn’t matter what database layer you use as they all share similar design patterns when it comes to data extraction into arrays.


Using PDO’s fetchAll() method you can do something like you want:

$html = '<ol>';

$results = $stmt->fetchAll();
foreach($results as $result){  
  foreach($result as $key => $value){
    $html .= "<li>$key : $value</li>";  }
$html .= '</ol>';
echo $html;


Thanks both so far for this insight. Since I’m still getting started, are you basically saying the the PDOStatement is a multidimensional array, so that’s why I have to use two loops to access the elements? For example, I use this simple code to access this array:


$myArray = array("Jim", "Betsy");

foreach ($myArray as $name){
	echo $name . "<br/>";


So my guess is that the PDOStatement object when used in a foreach loop, is not a simple single dimension array?

Again, sorry for the ignorance, just trying to get the hang of things!


Most returned db result sets are in a multi-dimensional array.

You can see this when you var_dump($results), it will show the data and depth to the arrays.


THAT is what I needed to know! :slight_smile:

Thanks again Steve,