PHP Arrays Introduction
In this page:
What is an Array
An array in PHP is a single ordered collection that can hold many values under one variable name, letting you group related data — like a list of usernames — instead of creating a separate variable for each item.
Example: What is an Array
<?php
$usernames = ["alice", "bob", "carol"];
print_r($usernames);
?>
Login to try C/C++/Java/PHP code in the editor
Printing Arrays
PHP arrays are unusually flexible: the same array() or [] structure can behave as a numerically indexed list, an associative key-value map, or a mix of both, unlike languages that force a strict choice between the two.
Example: Printing Arrays
<?php
$mixed = ["name" => "Alice", 0 => "first", 1 => "second"];
print_r($mixed);
?>
Login to try C/C++/Java/PHP code in the editor
Checking Array Size
You create an array with the short [] syntax (or the older array() function) and can nest arrays inside arrays to represent more complex structures, such as a list of orders where each order is itself an array of details.
Example: Checking Array Size
<?php
$orders = [
["id" => 1, "item" => "Book"],
["id" => 2, "item" => "Pen"],
];
print_r($orders);
?>
Login to try C/C++/Java/PHP code in the editor
Checking Array Types
count() tells you how many elements an array holds, which is essential before looping over it or validating that a form submitted the expected number of items.
Example: Checking Array Types
<?php
$items = ["a", "b", "c"];
echo count($items);
?>
Login to try C/C++/Java/PHP code in the editor
Iterating with Foreach
Arrays are passed by value by default in PHP, meaning a function that receives an array and modifies it is working on a copy unless you explicitly pass it by reference with an & — a detail that trips up many beginners.
Example: Iterating with Foreach
<?php
function addItem($arr) {
$arr[] = "new";
}
$list = ["a", "b"];
addItem($list);
print_r($list); // unchanged -- array was passed by value
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: