← 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
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Backend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account