Arrays

An array is a special variable, which can hold more than one value at a time. In PHP, there are three types of arrays: Indexed arrays, Associative arrays, and Multidimensional arrays.

Indexed Arrays

An indexed or numeric array stores each array element with a numeric index:

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Multidimensional Arrays

A multidimensional array is an array containing one or more arrays:

<?php
$cars = array(
    array("Volvo",22,18),
    array("BMW",15,13),
    array("Saab",5,2),
    array("Land Rover",17,15)
);

for ($row = 0; $row < 4; $row++) {
    echo "<p><b>Row number $row</b></p>";
    echo "<ul>";
    for ($col = 0; $col < 3; $col++) {
        echo "<li>".$cars[$row][$col]."</li>";
    }
    echo "</ul>";
}
?>

Arrays are an important data structure in PHP and offer a flexible way to organize and manipulate data.

Last updated