Indexed Array in PHP

In PHP, an indexed array is a type of array where each element is associated with a numeric index. The index starts from 0 for the first element and increments by 1 for each subsequent element. Indexed arrays are used to store ordered collections of data where the order of elements matters.

Here's how you can create and work with an indexed array in PHP:

Example
// Creating an indexed array
$colors = array("Red", "Green", "Blue");

// Accessing elements by index
echo $colors[0]; // Output: Red
echo $colors[1]; // Output: Green
echo $colors[2]; // Output: Blue

// Modifying elements
$colors[1] = "Yellow";
echo $colors[1]; // Output: Yellow

// Adding elements
$colors[] = "Orange";
echo $colors[3]; // Output: Orange

// Getting the length of the array
echo count($colors); // Output: 4

// Iterating over the array using a for loop
for ($i = 0; $i < count($colors); $i++) {
    echo $colors[$i] . "
"; }

In this example

  • We create an indexed array $colors with three elements: "Red", "Green", and "Blue".
  • We access elements of the array using their numeric indices ( $colors[0] , $colors[1] , $colors[2] ).
  • We modify the second element of the array to "Yellow".
  • We add a new element "Orange" to the end of the array using empty square brackets ( $colors[] ).
  • We use the count() function to determine the length of the array.
  • We iterate over the array using a for loop and output each element.

Indexed arrays are versatile and commonly used in PHP for tasks such as storing lists of items, iterating over data, and more. They provide a simple and efficient way to organize and manage ordered collections of data.

Next Article ❯