PHP Indexed Arrays - PHP Arrays
Updated: September 29th, 2022, 01:09:15 IST
Published:
September 28th, 2022
An array that uses an index number by default is known as a PHP indexed array. An index number that begins at zero is used to identify each element of an array. Objects, characters, and integers may all be stored in a PHP indexed array. A numeric array in PHP is sometimes referred to as an index array.
There are two ways to create indexed arrays:
First:
$size=array("XS","S","M","L","XL","XXL");
Second:
$size[0]="XS";
$size[1]="S";
$size[2]="M";
$size[3]="L";
$size[4]="XL";
$size[5]="XXL";
Example of an index array:
<?php
$size = array("Small", "Medium", "Large");
echo "Available sizes are " . $size[0] . ", " . $size[1] . " and " . $size[2] . ".";
?>
Output will be:
Available sizes are Small, Medium and Large.
Loop Through an Indexed Array in PHP
To loop through and print all the values of an indexed array, you could use a for loop, something like this:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array("One", "Two", "Three", "Four", "Five");
$array_length = count($numbers);
for($n = 0; $n < $array_length; $n++) {
echo $numbers[$n];
echo "<br>";
}
?>
</body>
</html>
Output:
One
Two
Three
Four
Five