PHP Indexed Arrays
PHP Indexed Arrays are a fundamental data structure used to store and manage an ordered collection of elements. Each element is assigned a unique numeric index (starting from 0).
Example
Create and display an indexed array:
<!DOCTYPE html> <html> <body> <pre> <?php $cars = array("Volvo", "BMW", "Toyota"); var_dump($cars); ?> </pre> </body> </html>
Output
array(3) {[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
• Access Indexed Arrays
To access an array item you can refer to the index number.
Example
Display the first array item:
<!DOCTYPE html> <html> <body> <?php $cars = array("Volvo", "BMW", "Toyota"); echo $cars[0]; ?> </body> </html>
Output
Volvo
• Change Value
To change the value of an array item, use the index number:
Example
Change the value of the second item:
<!DOCTYPE html> <html> <body> <pre> <?php $cars = array("Volvo", "BMW", "Toyota"); $cars[1] = "Ford"; var_dump($cars); ?> </pre> </body> </html>
Output
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
}
• Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a foreach loop, like this:
Example
Display all array items:
<!DOCTYPE html> <html> <body> <?php $cars = array("Volvo", "BMW", "Toyota"); foreach ($cars as $x) { echo "$x
"; } ?> </body> </html>
Output
Volvo
BMW
Toyota