Search notes:

PHP code snippets: foreach

foreach can be used to iterate over an array.

Values

foreach($ary as $val) iterates over the elements in an array and assigns each element's value to $val.
<html><head><title>Print indices and values of an array</title></head>
<body>

  <?php 
   
    $ary = array('one', 'two', 'three');
    
    foreach ($ary as $index => $val) {
        print "<br>$index: $val";
    }

  ?>

</body>
</html>
Github repository about-php, path: /array/foreach/indices-values.html

Indices and values

Similarly, foreach($ary as $index => $val) iterates over the elements in an array and assigns the each element's index to $index and their values to $val.
<html><head><title>Print indices and values of an array</title></head>
<body>

  <?php 
   
    $ary = array('one', 'two', 'three');
    
    foreach ($ary as $index => $val) {
        print "<br>$index: $val";
    }

  ?>

</body>
</html>
Github repository about-php, path: /array/foreach/indices-values.html

See also

Other PHP snippets

Index