Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Accessing All Array Elements in Nested Arrays

print_r($a);
<pre>
<?php
  $a = array(
    'Roman' =>
      array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'),
    'Arabic' =>
      array('one' => '1', 'two' => '2', 'three' => '3', 'four' => '4')
  );
  print_r($a);
?>
</pre>

Printing a Nested Array with print_r (print_r.php)

Nested arrays can be printed really easily by using print_r(). Take a look at the output of the listing in Figure 2.1.

Figure 2.1

Figure 2.1. Printing array contents with print_r()

However, the output of the preceding code (see Figure 2.1) is hardly usable for more than debugging purposes. Therefore, a clever way to access all data must be found. A recursive function is a reasonable way to achieve this. In this, all elements of an array are printed out; the whole output is indented using the HTML element <blockquote>. If the array element’s value is an array itself, however, the function calls itself recursively, which leads to an additional level of indention. Whether something is an array can be determined using the PHP function is_array(). Using this, the following code can be assembled; see Figure 2.2 for the result:

<?php
  function printNestedArray($a) {
    echo '<blockquote>';
    foreach ($a as $key => $value) {
      echo htmlspecialchars("$key: ");
      if (is_array($value)) {
        printNestedArray($value);
      } else {
        echo htmlspecialchars($value) . '<br />';
      }
    }
    echo '</blockquote>';
  }

  $arr = array(
    'Roman' =>
      array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'),
    'Arabic' =>
      array('one' => '1', 'two' => '2', 'three' => '3', 'four' => '4')
  );

  printNestedArray($arr);
?>

Printing a Nested Array Using a Recursive Function (printNestedArray.php)

Figure 2.2

Figure 2.2. Printing array contents using a recursive function

  • + Share This
  • 🔖 Save To Your Account