An array is a special variable that can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$car1 = "Volvo";
$car2 = "BMW";
$car3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? What if you had 300 cars? The solution is an Array!
In PHP, arrays can be created using the array() function or the shorter square bracket [] syntax.
<?php
$cars = array("Volvo", "BMW", "Toyota");
// OR
$cars = ["Volvo", "BMW", "Toyota"];
?>
There are three main types of arrays that you will use frequently:
The count() function is used to return the number of elements currently stored in an array.
<?php
$cars = ["Volvo", "BMW", "Toyota"];
echo count($cars); // Outputs: 3
?>
$array[0].
count() inside a loop's condition. for ($i = 0; $i < count($arr); $i++) recalculates the count on every single pass. Store it in a variable before the loop starts if the array size won't change.
sort() on an associative array. sort() re-indexes the array and discards the original string keys. Use asort() or ksort() instead to preserve key/value pairs while sorting.
$b = $a; makes an actual copy of the array by default — the opposite of JS objects. Use $b = &$a; if you specifically want a reference.
A second example — pairing student names with grades and looping over both the keys and values together:
<?php
$grades = ["Amina" => "A", "Karim" => "B", "Nadia" => "A"];
foreach ($grades as $student => $grade) {
echo "$student: $grade\n";
}
?>
Q: Are PHP arrays copied by value or reference?
A: By value, by default — assigning an array to a new variable makes an independent copy. Use & to force a reference instead.
Q: What's the difference between array() and []?
A: None functionally — [] is the shorter, modern syntax introduced in PHP 5.4, while array() is the older, more verbose form. Both create the exact same array.
Q: How do I loop through an associative array?
A: Use foreach ($array as $key => $value), as shown above. See the PHP manual's array reference for the full behavior across array types.