PHP Indexed Arrays

PHP Indexed Arrays are arrays where each element is assigned an index, which is usually a number starting from 0 by default. These are the most common type of arrays in PHP.

Creating Indexed Arrays

There are a few ways to create indexed arrays in PHP:

1. Using array() function

$fruits = array("Apple", "Banana", "Cherry");

2. Using short array syntax (PHP 5.4+)

$fruits = ["Apple", "Banana", "Cherry"];

3. Assigning values manually

$fruits[0] = "Apple"; $fruits[1] = "Banana"; $fruits[2] = "Cherry";

Accessing Elements

You can access an element by its index:

echo $fruits[1]; // Outputs: Banana

Looping Through an Indexed Array

Using for loop:

for ($i = 0; $i < count($fruits); $i++) { echo $fruits[$i] . "<br>"; }

Using foreach loop:

foreach ($fruits as $fruit) { echo $fruit . "<br>"; }

Modifying Values

$fruits[1] = "Blueberry"; // Changes Banana to Blueberry

Adding Elements

$fruits[] = "Date"; // Adds "Date" to the end of the array