PHP Indexed Arrays

An indexed array is the simplest form of an array. It uses numeric indexes to access elements. The first element has an index of 0, the second has an index of 1, and so on. Indexed arrays are ordered, and the order of elements is important. Elements in an indexed array are accessed and manipulated using their corresponding index.

Here’s an example of an indexed array in PHP:

$fruits = array("Apple", "Banana", "Orange", "Mango");

Alternatively, you can use the shorthand array syntax introduced in PHP 5.4:

$fruits = ["Apple", "Banana", "Orange", "Mango"];

In this example, we have created an indexed array called $fruits that contains four elements: “Apple“, “Banana“, “Orange“, and “Mango“. The indexes for these elements are 0, 1, 2, and 3, respectively.

You can access individual elements of an indexed array using their corresponding indexes.

For example:

echo $fruits[0];  // Output: Apple
echo $fruits[1];  // Output: Banana
echo $fruits[2];  // Output: Orange
echo $fruits[3];  // Output: Mango

You can also modify or assign values to specific indexes in the array:

$fruits[2] = "Grapes";  // Modify the value at index 2
$fruits[4] = "Pineapple";  // Assign a new value at index 4

Now, the array $fruits would contain: “Apple“, “Banana“, “Grapes“, “Mango“, “Pineapple“. Notice that assigning a value to an index that doesn’t exist in the array will automatically add a new element at that index.

You can use various array functions and loops to work with indexed arrays in PHP, such as count(), array_push(), array_pop(), foreach loop, and more. These functions and loops allow you to perform operations like adding or removing elements, iterating over the array, searching for specific values, and performing calculations.

Indexed arrays are commonly used when you have a collection of similar items or when you need to maintain the order of elements in the array. They provide a simple and efficient way to work with multiple values under a single variable name.