HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to PHPVariablesData TypesOperatorsStringsArraysAssociative ArraysConditions (if / else)Loops (for / foreach / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
PHP›Arrays

Arrays

Creating arrays, element access, adding, counting (count), and iterating with foreach.

Simple enough for a 5-year-old to understand

Create an array and access elements

Example code
1
<?php
Start.
DefinitionStart.
2
$colors = ["red", "purple", "green"];
An array with three elements.
DataAn array with three elements.
3
echo $colors[0];
First element: get (starts at 0!).
Output / InputFirst element: get (starts at 0!).
4
echo "\n";
New line.
Output / InputNew line.
5
echo count($colors);
Number of elements: 3
Output / InputNumber of elements: 3
DefinitionDataOutput / Input
💡 Hint: Short way to add an element to an array: $arr[] = "yeni";

About this topic

In PHP, an array combines two separate structures from other languages under one roof: an ordered list and a key-value map. Technically, every PHP array is an ordered map; a numerically indexed array is a special case where keys are numbers starting from 0.

This combined design provides flexibility: the same array can contain both numeric and string keys. However, it requires care — when you delete an element, the indexes are NOT RE-NUMBERED, leaving a gap.

PHP's array function library is very extensive: sorting, filtering, mapping, merging, searching. You can do most tasks with a single function without writing loops.

What you will learn

  • Creating arrays and short square bracket syntax
  • Adding and reading elements
  • Getting the number of elements with count
  • Iterating over arrays with foreach
  • Using array_push, array_pop, and in_array
  • Using sort, array_map, and array_filter functions

When to use?

Arrays are everywhere in PHP: form data, database rows, configuration, query strings — they all come as arrays. Writing PHP code largely consists of processing arrays.

array_map is used to transform elements, array_filter to filter them, and array_reduce to aggregate them. These functions express intent more clearly than a loop.

Common mistakes

Wrong

$items = ["a", "b", "c"];
unset($items[1]);
echo $items[1];

unset deletes the element but does NOT RE-NUMBER the indexes; 0 and 2 remain in the array, while 1 is gone. You get an "Undefined array key 1" warning. To re-index, use array_values.

Correct

$items = ["a", "b", "c"];
unset($items[1]);
$items = array_values($items);
echo $items[1];

Wrong

$items = ["a", "b", "c"];
for ($i = 0; $i <= count($items); $i++) {
    echo $items[$i];
}

Since less-than-or-equal is used in the condition, the loop runs one extra time and accesses a non-existent index on the last iteration; you get an "Undefined array key 3" warning. Using foreach when iterating over arrays completely prevents this error.

Correct

$items = ["a", "b", "c"];
foreach ($items as $item) {
    echo $item;
}

Wrong

$nums = [3, 1, 2];
$sorted = sort($nums);
print_r($sorted);

sort sorts the array IN PLACE and returns true, not the sorted array. Using the return value prints a boolean. If you want a sorted copy, you need to copy it first and then sort.

Correct

$nums = [3, 1, 2];
sort($nums);
print_r($nums);

Frequently asked questions

Should I use foreach or for?

Almost always foreach. You cannot make index errors, it also works with string-keyed arrays, and it clearly shows intent. for is only needed when you need to perform calculations on the index — for example, skipping by twos.

How do I print and inspect an array?

print_r prints a readable tree; var_dump also shows types and is more useful when debugging. Printing an array with echo only outputs "Array" and generates a warning.

Is copying an array by reference or by value?

Array assignment in PHP copies by VALUE — unlike objects. If you assign an array to another variable and modify it, the original array remains unaffected. This is a helpful behavior that sets PHP apart from most languages; if you want a reference, you must explicitly specify it.

Summary

A PHP array works as both a list and a map, and array assignment copies by value. unset does not re-index, sort sorts in place, and foreach is the safe way to iterate over arrays.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code