Looping through arrays with PHP

This tutorial explains how to loop through the elements in a PHP array. This works by using a for loop that will access elements in the array by their index. For each iteration of the loop, a different index will be accessed. You will also see how count() is used to count the number of elements in an array. The process for looping through each character in a string variable is basically the same as looping through each element in an array, as a string is basically an array of characters.

Watch the video below and then scroll down to see the sample code.

Sample PHP code to loop through each string element in an array and echo each element’s value on a new line:

<?php
  // create a new array
  $myArray = array("a","b","c");

  // loop through each element in the array
  // count will count all elements in an array
  for($i=0;$i<count($myArray);$i++){
    echo $myArray[$i] , "</br>";
  }
?>

Sample code to loop through an array and modify the value of each element in the array:

<?php
  // create a new array
  $myArray = array(1,2,3,4,5);

  // loop through each element in the array
  // count will count all elements in an array
  for($i=0;$i<count($myArray);$i++){
    // this will multiply each integer value by 2
    $myArray[$i] = $myArray[$i] * 2;
    echo $myArray[$i] , "</br>";
  }
?>