Arrays in PHP: Indexed Array, Associative Array, Multidimensional Array & Predefined Functions
1. Introduction to Arrays in PHP
An array is a special variable that can store multiple values in a single variable. Each value is stored with an index or key.
Why Use Arrays? • Store multiple related values • Reduce number of variables • Easy data management
2. Indexed Array
An indexed array uses numeric indexes (starting from 0 by default).
Declaration:
$subjects = array("HTML", "CSS", "PHP", "JavaScript");
Accessing Elements:
echo $subjects[0]; // HTML
Using Loop:
for ($i = 0; $i < count($subjects); $i++) {
echo $subjects[$i] . "<br>";
}
3. Associative Array
An associative array uses named keys instead of numeric indexes.
Declaration:
$student = array(
"name" => "Rohit",
"age" => 21,
"course" => "BCA"
);
Accessing Elements:
echo $student["name"];
Using foreach Loop:
foreach ($student as $key => $value) {
echo $key . " : " . $value . "<br>";
}
4. Multidimensional Array
A multidimensional array is an array containing one or more arrays.
Example:
$students = array(
array("Amit", 20, "BCA"),
array("Neha", 21, "BCA"),
array("Ravi", 22, "BCA")
);
Accessing Elements:
echo $students[0][0]; // Amit
Using Nested Loop:
for ($i = 0; $i < count($students); $i++) {
for ($j = 0; $j < count($students[$i]); $j++) {
echo $students[$i][$j] . " ";
}
echo "<br>";
}
5. PHP Array Predefined Functions
PHP provides many built-in functions to handle arrays.
Common Array Functions:
| Function | Description |
|---|---|
| count() | Count elements |
| sort() | Sort ascending |
| rsort() | Sort descending |
| array_push() | Add element at end |
| array_pop() | Remove last element |
| array_merge() | Merge arrays |
| in_array() | Check value exists |
| array_keys() | Get all keys |
| array_values() | Get all values |
Examples:
count()
echo count($subjects);
sort()
sort($subjects);
array_push()
array_push($subjects, "React");
in_array()
if (in_array("PHP", $subjects)) {
echo "Found";
}
6. Difference Between Indexed & Associative Array
| Feature | Indexed Array | Associative Array |
|---|---|---|
| Index Type | Numeric | Named |
| Access | Using index | Using key |
| Usage | Lists | Key–value data |