PHP Arrays – Indexed, Associative & Multidimensional
An array is a collection of data stored in a single variable, where each element is accessed using a numeric or string index. Arrays are very useful for managing collections of data like a list of names, numbers, or any other related information.
Types of Arrays in PHP
- Indexed Arrays: Arrays with numeric keys.
- Associative Arrays: Arrays with named keys.
- Multidimensional Arrays: Arrays containing other arrays.
1. Indexed Arrays
An indexed array uses numbers (starting from 0) as keys.
Creating an Indexed Array:
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");
echo $person["name"]; // Outputs: John
?>
Alternative Syntax:
<?php $person = ["name" => "John", "age" => 30, "city" => "New York"]; echo $person["age"]; // Outputs: 30 ?>
Adding Element:
<?php $person["country"] = "USA"; print_r($person); // Outputs: Array ( [name] => John [age] => 30 [city] => New York [country] => USA ) ?>
3. Multidimensional Arrays
These are arrays that contain other arrays.
Creating a Multidimensional Array
<?php
$students = [
["Anaya", 20, "A"],
["Henry", 25, "B"],
["Oliver", 22, "B"],
["Aarush", 24, "A"]
];
echo $students[1][0]; // Outputs: Henry
?>
Associative Multidimensional Array
<?php
$students = [
["name" => "Anaya", "age" => 20, "grade" => "A"],
["name" => "Henry", "age" => 25, "grade" => "B"],
["name" => "Oliver", "age" => 25, "grade" => "B"]
];
echo $students[0]["grade"]; // Outputs: A
?>
Array Functions
PHP provides many built-in functions to work with arrays:
| Function | Description | Example |
|---|---|---|
count() |
Counts the elements in an array | count($array) |
array_push() |
Adds one or more elements to the end of an array | array_push($array, "Mango") |
array_pop() |
Removes the last element of an array | array_pop($array) |
array_merge() |
Merges two or more arrays | array_merge($arr1, $arr2) |
in_array() |
Checks if a value exists in an array | in_array("Apple", $fruits) |
array_keys() |
Returns all the keys of an array | array_keys($person) |
array_values() |
Returns all the values of an array | array_values($person) |
Example:
<?php $colors = ["Red", "Green", "Blue"]; echo count($colors); // Outputs: 3 ?>
Looping Through Arrays
1. Indexed Array with for
<?php
$fruits = ["Apple", "Banana", "Mango"];
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "\n";
}
?>
2. Associative Array with foreach
<?php
$person = ["name" => "James", "age" => 25];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
// Outputs:
// name: James
// age: 25
?>
Summary
- Indexed arrays use numbers as keys.
- Associative arrays use named keys.
- Multidimensional arrays contain other arrays.
- Use PHP’s built-in array functions to make working with arrays easier.