← PHP tutorial

PHP

Loops

for and while loops work like most C-family languages. foreach is PHP's dedicated way to step through every item in an array without managing an index yourself.

Example: for vs. foreach

<?php
  $total = 0;
  for ($i = 1; $i <= 5; $i++) {
    $total += $i;
  }
  echo "Total: $total";
?>
Total: 15

for is the right tool when you need the index itself (counting, or accessing items by position); foreach, covered properly in the Arrays lesson next, is the right tool the moment you just need each value in turn and don't care about tracking a numeric index — which describes most real loops over array data.

Example
<?php
  $total = 0;
  for ($i = 1; $i <= 5; $i++) {
    $total += $i;
  }
  echo "Total: $total";
?>
Output
Total: 15