Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable and are widely used in almost every PHP application.
In this guide, you'll learn the three main types of arrays in PHP: indexed, associative, and multidimensional arrays, with practical examples.
What Is an Array in PHP?
An array is a variable that can hold multiple values at once.
<?php
$colors = ["red", "green", "blue"];
Types of PHP Arrays
1. Indexed Arrays
Indexed arrays use numeric keys starting from 0.
$fruits = ["apple", "banana", "orange"];
echo $fruits[0]; // apple
Looping through indexed arrays:
foreach ($fruits as $fruit) {
echo $fruit;
}
2. Associative Arrays
Associative arrays use named keys instead of numbers.
$user = [
"name" => "John",
"age" => 30
];
echo $user["name"]; // John
Looping through associative arrays:
foreach ($user as $key => $value) {
echo $key . ": " . $value;
}
3. Multidimensional Arrays
A multidimensional array contains one or more arrays inside it.
$users = [
["name" => "John", "age" => 30],
["name" => "Jane", "age" => 25]
];
echo $users[0]["name"]; // John
Looping through multidimensional arrays:
foreach ($users as $user) {
echo $user["name"];
}
Common Array Functions
count()– count elementsarray_push()– add elementarray_pop()– remove last elementarray_merge()– merge arraysin_array()– check value existence
Example: Real-World Usage
<?php
$products = [
["name" => "Laptop", "price" => 1000],
["name" => "Phone", "price" => 500]
];
foreach ($products as $product) {
echo $product["name"] . " - $" . $product["price"];
}
Best Practices
- Use associative arrays for structured data
- Keep array structure consistent
- Use built-in functions instead of manual loops when possible
Common Mistakes
- Accessing undefined indexes
- Mixing numeric and string keys unintentionally
- Not checking if a key exists
FAQ
What is the difference between indexed and associative arrays?
Indexed arrays use numeric keys, while associative arrays use named keys.
What is a multidimensional array?
It is an array that contains other arrays.
How do I loop through an array in PHP?
Use foreach for easy iteration.
How do I check if a value exists in an array?
Use in_array().
Conclusion
PHP arrays are flexible and powerful. By understanding indexed, associative, and multidimensional arrays, you can manage complex data structures efficiently.