An array in PHP is a single variable that can hold multiple values. Instead of creating multiple variables, we use an array to store and organize related data.
PHP supports three types of arrays:
✔ Elements are stored with numeric keys (starting from 0).
Example:
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
✔ Uses named keys instead of numbers.
$person = ["name" => "John", "age" => 25, "city" => "New York"];
echo $person["name"]; // Output: John
✔ Stores arrays inside another array.
$students = [
["John", 22, "A"],
["Alice", 21, "B"],
["Mark", 23, "A"]
];
echo $students[0][0]; // Output: John
✔ 0,0
refers to the first row, first column.
foreach ($students as $student) {
echo "Name: " . $student[0] . ", Age: " . $student[1] . ", Grade: " . $student[2] . "<br>";
}
PHP provides built-in functions for working with arrays:
Function | Description |
---|---|
count($array) |
Returns the number of elements |
array_push($array, $value) |
Adds an element at the end |
array_pop($array) |
Removes the last element |
array_shift($array) |
Removes the first element |
array_unshift($array, $value) |
Adds an element at the beginning |
array_merge($array1, $array2) |
Combines two arrays |
in_array($value, $array) |
Checks if a value exists |
array_keys($array) |
Returns an array of keys |
array_values($array) |
Returns an array of values |
$numbers = [1, 2, 3];
array_push($numbers, 4); // Adds 4 to the array
print_r($numbers); // Output: [1, 2, 3, 4]
✔ Arrays store multiple values in one variable.
✔ Indexed arrays use numeric keys, associative arrays use named keys.
✔ Multidimensional arrays store arrays inside arrays.
✔ PHP provides useful array functions to manipulate data efficiently. 🚀