Arrays
PHP arrays are remarkably flexible, functioning as both simple numbered lists and associative key-value maps within the same underlying data structure.
Indexed and Associative Arrays
An indexed array uses automatic numeric keys starting at 0. An associative array uses explicit string (or custom numeric) keys, letting you label each value meaningfully.
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
$student = [
"name" => "Palesa",
"age" => 22,
"course" => "PHP"
];
echo $student["name"]; // Palesa
Useful Array Functions
PHP's built-in array functions cover most everyday needs without writing manual loops.
count($arr)— number of elements.array_push($arr, $val)— add an element to the end.in_array($val, $arr)— check whether a value exists.array_map($fn, $arr)— apply a function to every element, returning a new array.sort($arr)— sort an indexed array's values.
Common Mistakes
- Confusing => (used for array key-value pairs) with = (assignment).
- Assuming array keys are always sequential after removing elements — deleting an item can leave gaps in numeric keys.
- Modifying an array's structure while looping over it with foreach without using a reference, causing unexpected behaviour.
- Forgetting that sort() re-indexes numeric keys, which can be surprising for an associative-style array with meaningful numeric keys.
Professional Tip
Use print_r($array) or var_dump($array) whenever you're unsure what an array actually contains — this is one of the fastest ways to debug array-related PHP code.
Your Turn
Create an associative array representing a product with name, price, and stock quantity, then write a function that accepts the array and returns a formatted string describing it.
Mini Quiz
What syntax is used to define key-value pairs in a PHP associative array?