Core PHP

Using Foreach as List Loops

This PHP code is an example program that demonstrates how to use foreach as list loops.

ForeachAsList.php

<?php

  // Create an array of arrays of elements.
  $iaaArray = [
    [3, 4, 8],
    [7, 2, 1],
    [0, 5, 9],
    [2, 2, 2]
  ];

  // Use a list and a foreach loop to assign names to the variables in each array.
  foreach ($iaaArray as list($iX, $iY, $iZ)) {
    echo "iX = ".$iX." : iY = ".$iY." : iZ = ".$iZ."<br />";
  }

  echo "<h4>Fetch only the first and third values.</h4>";
  // Use only two variables to get only the first and third values in each array.
  foreach ($iaaArray as list($iA, ,$iB)) {
      echo "iA = ".$iA." : iB = ".$iB."<br />";
  }

?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.