PrimitiveType

PHP: foreach loop

<?php $myArray = array('guitar', 'piano', 'saxophone', 'trumpet', 'violin'); // The easiest way to loop through an array is with a foreach loop foreach ($myArray as $item) { echo $item . PHP_EOL; } /* Prints: guitar piano saxophone trumpet violin */ // You can also get the current key in a foreach loop foreach ($myArray as $key => $item) { echo $key . ' => ' . $item . PHP_EOL; } /* Prints: 0 => guitar 1 => piano 2 => saxophone 3 => trumpet 4 => violin */ // You can also get a reference to the individual items - but be careful to unset $item afterwards foreach ($myArray as &$item) { // modify $item somehow $item .= ' player'; } unset($item); // unset $item to avoid unexpected behaviour var_dump($myArray); /* Prints: array(5) { [0]=> string(13) "guitar player" [1]=> string(12) "piano player" [2]=> string(16) "saxophone player" [3]=> string(14) "trumpet player" [4]=> string(13) "violin player" } */