PHP Arrays: A Practical Guide
An array stores multiple values in a single variable. PHP arrays are flexible: they can use integer or string keys and can contain values of different types.
Indexed Arrays
An indexed array uses numeric keys, commonly starting at zero:
$colors = ["red", "green", "blue"];
echo $colors[0]; // red
Add an item with $colors[] = "yellow". Use count($colors) to get the number of elements.
Associative Arrays
Associative arrays use named keys:
$user = [
"name" => "Alex",
"email" => "alex@example.com"
];
echo $user["name"];
They are useful for representing records and configuration values. Always check that a key exists before relying on optional data; isset() and array_key_exists() have slightly different behavior when a value is null.
Looping Through Arrays
foreach is the common way to iterate over an array:
foreach ($colors as $color) {
echo $color;
}
For key-value pairs, use foreach ($user as $key => $value). This makes the relationship between each key and value explicit.
Multidimensional Arrays
An array can contain other arrays. For example, a list of users can be represented as an array where each item contains name and email keys. Access nested values by following each key in sequence.
Useful Array Functions
Common functions include array_map() for transforming values, array_filter() for selecting values, array_merge() for combining arrays, and in_array() for checking whether a value exists. Read each function's documentation carefully, particularly when keys need to be preserved.
Conclusion
Arrays are central to everyday PHP development. Choose indexed arrays for ordered lists and associative arrays for key-value records, then use foreach and the built-in array functions to keep data handling clear.