← Back to PHP Course | Chapter 7: Arrays | Lesson 1 of 13

PHP Arrays Introduction

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
<?php
$usernames = ["alice", "bob", "carol"];
print_r($usernames);
?>

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
<?php
$mixed = ["name" => "Alice", 0 => "first", 1 => "second"];
print_r($mixed);
?>

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
<?php
$orders = [
    ["id" => 1, "item" => "Book"],
    ["id" => 2, "item" => "Pen"],
];
print_r($orders);
?>

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
<?php
$items = ["a", "b", "c"];
echo count($items);
?>

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
<?php
function addItem($arr) {
    $arr[] = "new";
}
$list = ["a", "b"];
addItem($list);
print_r($list); // unchanged -- array was passed by value
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.