Google News
logo
PHP Program to Indexed Arrays
In the following example of PHP program that demonstrates how to create and work with indexed arrays :
Program :
<?php

// Create an indexed array
$fruits = array("apple", "banana", "orange", "kiwi");

// Access and print the values of the array
echo "The first fruit in the array is: " . $fruits[0] . "<br>";
echo "The second fruit in the array is: " . $fruits[1] . "<br>";
echo "The third fruit in the array is: " . $fruits[2] . "<br>";
echo "The fourth fruit in the array is: " . $fruits[3] . "<br>";

// Add a new element to the array
$fruits[] = "grape";

// Access and print the updated values of the array
echo "The fifth fruit in the array is: " . $fruits[4] . "<br>";

?>
Output :
The first fruit in the array is: apple
The second fruit in the array is: banana
The third fruit in the array is: orange
The fourth fruit in the array is: kiwi
The fifth fruit in the array is: grape
In the above example, we have created an indexed array `$fruits` using the `array()` function with four elements: "apple", "banana", "orange", and "kiwi". We access and print the values of the array using the index numbers starting from `0`.

We then add a new element "grape" to the array using the `$fruits[]` syntax. We access and print the updated values of the array using the index number `4`.

Indexed arrays are one of the most basic and widely used types of arrays in PHP. They allow us to store multiple values of the same data type in a single variable and access them using an index number.