PHP Arrays

JA JASWANT Updated 30 Oct 2026
7 min read ·Lesson 196 of 209

What Is an Array?

In simple terms: An array is a single variable that holds many values. Instead of creating $student1, $student2, $student3, … you store all students in one array and work with them as a group. Technically: A PHP array is an ordered map: a collection of key → value pairs that remembers the order in which elements were added. Keys are integers or strings; values can be of any type, including other arrays. The same structure serves as a list, a dictionary, a stack, a queue, or a table of records.

Why Arrays Are Essential

Without arrays:

$product1 = 'Keyboard';
$product2 = 'Mouse';
$product3 = 'Monitor';
// How many products are there? How do you loop over them?

With an array:

<?php
$products = ['Keyboard', 'Mouse', 'Monitor'];
echo count($products) . " products\n";
foreach ($products as $product) {
    echo "- $product\n";
}

Output

3 products
- Keyboard
- Mouse
- Monitor

Arrays make it possible to count, loop over, search, sort, filter, and transform collections of any size. Database results, form submissions, configuration, and decoded JSON all arrive in PHP as arrays.


Creating Arrays

$colors = ['red', 'green', 'blue'];
$user = ['name' => 'Asha', 'age' => 24];
$empty = [];

Long Syntax

$colors = array('red', 'green', 'blue');

Both create identical arrays. The short [] syntax (available since PHP 5.4) is the modern standard; you will see array() in older code.


Keys and Values

Every element has a key and a value:

<?php
$product = [
    'name' => 'Desk Lamp',
    'price' => 1299.0,
    'tags' => ['home', 'lighting'],
    'inStock' => true,
];
var_dump($product);

Output

array(4) {
  ["name"]=>
  string(9) "Desk Lamp"
  ["price"]=>
  float(1299)
  ["tags"]=>
  array(2) {
    [0]=>
    string(4) "home"
    [1]=>
    string(8) "lighting"
  }
  ["inStock"]=>
  bool(true)
}

What This Shows

  • array(4) — the array has four elements.
  • ["name"]=> — a string key.
  • Values have different types: string, float, array, and boolean.
  • tags contains a nested array with integer keys 0 and 1. var_dump() shows types and lengths; print_r() shows a shorter, human-friendly view. Both are debugging tools.

The Three Common Kinds of Arrays

PHP has only one array type, but it is commonly used in three ways:

KindKeysExampleTypical UseLesson
Indexed0, 1, 2, … (automatic)['Mango', 'Banana']ListsIndexed Arrays
AssociativeMeaningful strings['name' => 'Asha', 'city' => 'Chennai']Records, settings, lookupsAssociative Arrays
MultidimensionalArrays inside arrays[['id' => 1, 'name' => 'Asha'], ...]Tables, nested dataMultidimensional Arrays
<?php
$fruits = ['Mango', 'Banana', 'Guava'];                       // indexed
$user = ['name' => 'Asha', 'city' => 'Chennai'];              // associative
$orders = [                                                   // multidimensional
    ['id' => 101, 'total' => 1250],
    ['id' => 102, 'total' => 640],
];
echo $fruits[0] . "\n";
echo $user['city'] . "\n";
echo $orders[1]['total'] . "\n";

Output

Mango
Chennai
640
  • Indexed arrays are accessed by position, starting at 0.
  • Associative arrays are accessed by name.
  • Multidimensional arrays use one bracket per level: $orders[1]['total'] is "the total of the second order".

Basic Operations

<?php
$cart = ['Pen', 'Notebook'];
$cart[] = 'Eraser';              // add to the end
$cart[0] = 'Gel Pen';            // update an element
unset($cart[1]);                 // remove an element
echo count($cart) . " items\n";
print_r($cart);
var_dump(in_array('Eraser', $cart, true));

Output

2 items
Array
(
    [0] => Gel Pen
    [2] => Eraser
)
bool(true)
OperationSyntaxLesson
Read an element$array[$key]Access Array Items
Update an element$array[$key] = $value;Update Array Items
Add to the end$array[] = $value;Add Array Items
Remove an elementunset($array[$key]);Remove Array Items
Count elementscount($array)Array Functions
Check for a valuein_array($value, $array, true)Search in Arrays

Notice that unset() removed key 1 but did not renumber the remaining keys — Eraser still has key 2. This is explained in Remove Array Items.


Arrays Are Ordered Maps

PHP arrays keep elements in insertion order, regardless of key type, and can mix integer and string keys:

<?php
$data = [5 => 'five', 'x' => 'ex', 1 => 'one'];
$data[] = 'next';
print_r($data);

Output

Array
(
    [5] => five
    [x] => ex
    [1] => one
    [6] => next
)
  • Elements appear in the order they were added, not sorted by key.
  • $data[] = ... uses the largest integer key so far plus one (5 + 1 = 6).
  • Keys can only be integers or strings. Other key types are converted — for example, "8" becomes 8 and true becomes 1 (see PHP Type Juggling).

Arrays Are Copied on Assignment

Arrays are values, not references. Assigning an array to another variable creates an independent copy:

<?php
$original = ['red', 'green'];
$copy = $original;
$copy[] = 'blue';
echo count($original) . " / " . count($copy) . "\n";

Output

2 / 3

The same applies when passing an array to a function. PHP uses copy-on-write, so the actual copying happens only if one of the arrays is modified — passing large arrays around is cheap.


Looping Over Arrays

foreach is the standard way to process every element:

<?php
$stock = ['Keyboard' => 12, 'Mouse' => 0, 'Monitor' => 4];
foreach ($stock as $product => $quantity) {
    echo "$product: $quantity\n";
}

Output

Keyboard: 12
Mouse: 0
Monitor: 4

See Foreach Loop for details, including modifying arrays during a loop.


Built-in Array Functions

PHP provides around 80 array functions. The most important groups:

PurposeExamplesLesson
Counting and checkingcount(), array_key_exists(), in_array(), array_is_list()Search in Arrays
Adding and removingarray_push(), array_pop(), array_shift(), array_unshift(), array_splice()Add / Remove Array Items
Sortingsort(), rsort(), asort(), ksort(), usort()Sorting Arrays
Combiningarray_merge(), array_combine(), +Merge Arrays
Transformingarray_map(), array_filter(), array_reduce()array_map / array_filter / array_reduce
Extractingarray_keys(), array_values(), array_column(), array_slice()Array Functions
Calculatingarray_sum(), array_product(), max(), min()Array Functions

Arrays and JSON

APIs exchange data as JSON, which maps naturally onto PHP arrays:

<?php
$product = ['id' => 7, 'name' => 'Desk Lamp', 'tags' => ['home', 'lighting']];
$json = json_encode($product);
echo $json . "\n";
$decoded = json_decode($json, true);
echo $decoded['tags'][1] . "\n";

Output

{"id":7,"name":"Desk Lamp","tags":["home","lighting"]}
lighting
  • Associative arrays become JSON objects ({...}); lists become JSON arrays ([...]).
  • json_decode($json, true) converts JSON back into associative arrays. Without true, JSON objects become stdClass objects.

Practical Example: A Simple Gradebook

<?php
$scores = ['Asha' => 88, 'Bala' => 72, 'Charu' => 95, 'Dev' => 64];
$passMark = 70;
$average = array_sum($scores) / count($scores);
$topScore = max($scores);
$topStudent = array_search($topScore, $scores, true);
$passed = array_filter($scores, fn(int $score): bool => $score >= $passMark);
arsort($scores);
echo "Average: $average\n";
echo "Top student: $topStudent ($topScore)\n";
echo "Passed: " . count($passed) . " of " . count($scores) . "\n";
echo "Ranking:\n";
$rank = 1;
foreach ($scores as $name => $score) {
    echo "  $rank. $name — $score\n";
    $rank++;
}

Output

Average: 79.75
Top student: Charu (95)
Passed: 3 of 4
Ranking:
  1. Charu — 95
  2. Asha — 88
  3. Bala — 72
  4. Dev — 64

Step-by-Step Explanation

  1. The associative array maps each student's name to a score.
  2. array_sum() and count() give the average: 319 / 4 = 79.75.
  3. max() finds the highest score, and array_search() finds the key (student name) with that value.
  4. array_filter() keeps only passing scores.
  5. arsort() sorts by score in descending order while keeping the names as keys.
  6. The loop prints the ranking with a counter. Each of these functions is explained in the lessons of this section.

Common Mistakes

Reading a Key That Does Not Exist

Effect: Warning: Undefined array key. Fix: Check with isset() or use a default: $user['phone'] ?? 'not provided'.

Expecting unset() to Renumber Keys

Effect: Gaps in indexed arrays, and for loops that read missing keys. Fix: Use foreach, or re-index with array_values().

Using + to Append Lists

Effect: [1, 2] + [3, 4, 5] gives [1, 2, 5], because + keeps existing keys. Fix: Use array_merge() or [...$a, ...$b].

Echoing an Array

Effect: Prints Array with an "Array to string conversion" warning. Fix: Use implode(), a loop, print_r(), or json_encode().

Loose Searching

Effect: in_array('1e1', ['10']) is true. Fix: Pass true as the third argument for strict comparison.


Best Practices

  • Use the short [] syntax.
  • Use indexed arrays for lists and associative arrays for records and lookups.
  • Use foreach to loop over arrays.
  • Use strict comparisons in search functions.
  • Prefer built-in array functions to hand-written loops for common tasks.
  • For complex records used throughout an application, consider classes with typed properties instead of large associative arrays. Official reference: https://www.php.net/manual/en/language.types.array.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions
Ask about this post
AI Ask about this post

Ask questions about PHP Arrays and get answers drawn from it.

Signed-in readers only.