In PHP, an array is a data structure that stores multiple values in a single variable. Each value in an array is called an element, and each element is associated with a unique index. Here’s an overview of PHP arrays:
An indexed array is an array where each element is assigned a numerical index, starting from zero.
Declaration and Initialization:
$colors = array("Red", "Green", "Blue"); // Using array() function
$fruits = ["Apple", "Banana", "Orange"]; // Using square brackets (PHP 5.4+)
echo $colors[0]; // Output: Red
echo $fruits[2]; // Output: Orange
An associative array is an array where each element is associated with a specific key instead of numerical indexes.
Declaration and Initialization:
$person = array("name" => "John", "age" => 30, "city" => "New York");
echo $person["name"]; // Output: John
echo $person["age"]; // Output: 30
A multidimensional array is an array containing one or more arrays as its elements. These arrays can be indexed arrays, associative arrays, or a combination of both.
$students = array(
array("name" => "John", "age" => 20),
array("name" => "Alice", "age" => 22),
array("name" => "Bob", "age" => 21)
);
echo $students[0]["name"]; // Output: John
echo $students[1]["age"]; // Output: 22