PHP

PHP Indexed Array Looping


Looping in Indexed based array:

In PHP, there are several ways to loop through an indexed (numerically indexed) array. Here are some common methods:


1.Using a for loop:

<?php
    $indexedArray = array(1, 2, 3, 4, 5);
    $arrayLength = count($indexedArray);

    for ($i = 0; $i < $arrayLength; $i++) {
        echo "Index: $i, Value: " . $indexedArray[$i] . "<br>";
    }
?>

 

In this example:

  1. count($indexedArray) is used to get the length of the array.
  2. The for loop initializes a counter variable $i to 0, checks if it is less than the array length, and increments it after each iteration.
  3. Inside the loop, echo "Index: $i, Value: " . $indexedArray[$i] . "<br>"; prints the current index and value of the array.

 

Output:

 

2.  Using a ‘foreach’ Loop:

<?php
    $indexedArray = array(1, 2, 3, 4, 5);

    foreach ($indexedArray as $index => $value) {
        echo "Index: $index, Value: $value<br>";
    }
?>

 

In this example:

  1. The foreach loop iterates over each element in the array.
  2. $index represents the index of the current element, and $value represents the value of the current element.
  3. Inside the loop, echo "Index: $index, Value: $value<br>"; prints the current index and value of the array.

 

Output:

 

Note: Using a foreach loop is often preferred for iterating through arrays in PHP, especially when dealing with indexed arrays, as it simplifies the syntax and eliminates the need for managing indices manually.