Create Arrays

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

There are many ways to create an array in PHP: writing it out literally, generating it with a function, converting it from a string or JSON, or building it step by step in a loop. Choosing the right technique makes code shorter and clearer. This lesson covers each approach and when to use it.


Array Literals

Short Syntax []

<?php
$colors = ['red', 'green', 'blue'];
$user = ['name' => 'Asha', 'city' => 'Chennai'];
$empty = [];
var_dump(count($colors), count($user), count($empty));

Output

int(3)
int(2)
int(0)
  • Without keys, values receive automatic integer keys 0, 1, 2, ….
  • With key => value, you choose the keys.
  • [] creates an empty array, ready to be filled.

Long Syntax array()

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

array() is a language construct that creates exactly the same array. It was the only syntax before PHP 5.4 and still appears in older code. Use [] in new code.

Multi-line Literals and Trailing Commas

<?php
$config = [
    'app_name' => 'GoCourse',
    'debug' => false,
    'timezone' => 'Asia/Kolkata',
    'supported_languages' => ['en', 'ta', 'hi'],
];
echo $config['supported_languages'][1] . "\n";

Output

ta

A trailing comma after the last element is allowed. It makes adding or reordering lines easier and keeps version-control diffs clean.


Mixing Explicit and Automatic Keys

<?php
$items = [5 => 'five', 'six', 'name' => 'mixed', 'seven'];
print_r($items);

Output

Array
(
    [5] => five
    [6] => six
    [name] => mixed
    [7] => seven
)

When no key is given, PHP uses the largest integer key so far plus one. String keys do not affect this counter. Mixing styles like this is legal but confusing; in practice, an array is usually either a list (automatic keys) or a map (explicit keys).

Duplicate Keys: The Last Value Wins

<?php
$settings = ['theme' => 'light', 'language' => 'en', 'theme' => 'dark'];
print_r($settings);

Output

Array
(
    [theme] => dark
    [language] => en
)

An array cannot contain the same key twice. The later value replaces the earlier one, but the key keeps its original position. Duplicate keys in a literal are usually a typo; static analysis tools report them.


Functions That Create Arrays

FunctionCreatesExample
range($start, $end, $step)A sequence of numbers or lettersrange(1, 5)
array_fill($startIndex, $count, $value)$count copies of a valuearray_fill(0, 3, 'TBD')
array_fill_keys($keys, $value)Given keys, all with the same valuearray_fill_keys(['a', 'b'], 0)
array_combine($keys, $values)Keys from one array, values from anotherarray_combine(['IN'], ['India'])
array_pad($array, $size, $value)An array extended to a given sizearray_pad([1, 2], 5, 0)
explode($separator, $string)Pieces of a stringexplode(',', 'a,b,c')
str_split($string, $length)Fixed-size chunks of a stringstr_split('ABCDEF', 2)
compact('var1', 'var2')An array from existing variablescompact('name', 'city')
json_decode($json, true)An array from JSONjson_decode('[1,2]', true)

Example

<?php
print_r(range(0, 20, 5));
print_r(array_fill(0, 3, 'TBD'));
print_r(array_fill_keys(['name', 'email', 'phone'], ''));
print_r(array_combine(['IN', 'JP'], ['India', 'Japan']));
print_r(array_pad([1, 2], 5, 0));

Output

Array
(
    [0] => 0
    [1] => 5
    [2] => 10
    [3] => 15
    [4] => 20
)
Array
(
    [0] => TBD
    [1] => TBD
    [2] => TBD
)
Array
(
    [name] => 
    [email] => 
    [phone] => 
)
Array
(
    [IN] => India
    [JP] => Japan
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 0
    [3] => 0
    [4] => 0
)

Where Each Is Useful

  • range() — page numbers, years for a dropdown, test data.
  • array_fill() — placeholders, such as empty slots in a schedule.
  • array_fill_keys() — a form's default values, or counters initialized to 0 for known categories.
  • array_combine() — pairing two lists (for example, CSV headers with a CSV row). Both arrays must have the same number of elements, or PHP throws a ValueError.
  • array_pad() — making rows the same length before building a table.

From Strings

<?php
$csvLine = 'php,mysql,laravel';
$tags = explode(',', $csvLine);
$code = 'AB12CD34';
$chunks = str_split($code, 2);
echo implode(' | ', $tags) . "\n";
echo implode('-', $chunks) . "\n";

Output

php | mysql | laravel
AB-12-CD-34

From Variables: compact()

<?php
$name = 'Asha';
$city = 'Chennai';
$age = 24;
$user = compact('name', 'city', 'age');
print_r($user);

Output

Array
(
    [name] => Asha
    [city] => Chennai
    [age] => 24
)

compact() builds an array whose keys are the variable names. It is common in older templates and some frameworks for passing variables to views. Writing the array explicitly (['name' => $name, ...]) is often clearer, and editors can track it better.

From JSON

<?php
$json = '{"title": "PHP Arrays", "lessons": 16, "topics": ["indexed", "associative"]}';
$course = json_decode($json, true);
echo $course['title'] . ' has ' . $course['lessons'] . " lessons\n";
echo 'First topic: ' . $course['topics'][0] . "\n";

Output

PHP Arrays has 16 lessons
First topic: indexed

The second argument true returns associative arrays instead of objects. Invalid JSON returns null; use the JSON_THROW_ON_ERROR flag to get an exception instead (see PHP JSON).


Building Arrays Dynamically

In a Loop

<?php
$squares = [];
for ($n = 1; $n <= 5; $n++) {
    $squares[] = $n * $n;
}
echo implode(', ', $squares) . "\n";

Output

1, 4, 9, 16, 25

Start with an empty array and append with $array[] = .... Initializing $squares = [] first is important: it guarantees the variable is an array even if the loop runs zero times.

With array_map()

<?php
$squares = array_map(fn(int $n): int => $n * $n, range(1, 5));
echo implode(', ', $squares) . "\n";

Output

1, 4, 9, 16, 25

Generating the input with range() and transforming it with array_map() produces the same result in one expression.

By Combining Arrays

<?php
$basics = ['Variables', 'Strings'];
$advanced = ['Closures', 'Generators'];
$syllabus = [...$basics, 'Arrays', ...$advanced];
echo implode(' → ', $syllabus) . "\n";

Output

Variables → Strings → Arrays → Closures → Generators

The spread operator ... copies elements from other arrays into a new array literal. See Array Spread Operator.

From Generators and Iterators

<?php
function evenNumbers(int $limit): Generator
{
    for ($n = 2; $n <= $limit; $n += 2) {
        yield $n;
    }
}
$evens = iterator_to_array(evenNumbers(10));
echo implode(', ', $evens) . "\n";

Output

2, 4, 6, 8, 10

iterator_to_array() collects all values produced by a generator or iterator into an array. Generators are covered in PHP Generators.


Practical Example: An Event Seat Map

<?php
$rows = range('A', 'C');
$seatsPerRow = 4;
$seats = array_fill_keys($rows, array_fill(1, $seatsPerRow, 'free'));
$seats['B'][2] = 'taken';
$seats['C'][4] = 'taken';
foreach ($seats as $row => $rowSeats) {
    $symbols = array_map(fn(string $status): string => $status === 'free' ? '○' : '●', $rowSeats);
    echo $row . ' ' . implode(' ', $symbols) . "\n";
}
$freeCount = 0;
foreach ($seats as $rowSeats) {
    $freeCount += count(array_keys($rowSeats, 'free', true));
}
echo "Free seats: $freeCount\n";

Output

A ○ ○ ○ ○
B ○ ● ○ ○
C ○ ○ ○ ●
Free seats: 10

Step-by-Step Explanation

  1. range('A', 'C') creates the row letters ['A', 'B', 'C'].
  2. array_fill(1, 4, 'free') creates one row of seats numbered 1 to 4 (seat numbers start at 1, as people expect).
  3. array_fill_keys() gives each row letter its own copy of that row, producing a two-level array.
  4. Individual seats are updated with two keys: $seats['B'][2].
  5. For display, array_map() converts statuses to symbols.
  6. array_keys($rowSeats, 'free', true) returns the keys whose value is exactly 'free'; counting them gives the free seats per row. Because arrays are copied on assignment, each row is independent — changing row B does not affect rows A or C.

Common Mistakes

Not Initializing Before Appending

Effect: If a loop never runs, the variable is undefined later; appending to a variable holding false triggers a deprecation notice since PHP 8.1. Fix: Initialize with $items = []; before the loop.

Duplicate Keys in Literals

Effect: Earlier values are silently overwritten. Fix: Check literals carefully; use a static analyzer.

array_combine() With Different Lengths

Effect: ValueError. Fix: Ensure both arrays have the same count (for example, validate CSV rows against headers).

Forgetting true in json_decode()

Effect: You get stdClass objects, and $data['key'] fails. Fix: json_decode($json, true) for arrays.


Best Practices

  • Use [] literals with trailing commas for fixed data.
  • Use range(), array_fill(), array_fill_keys(), and array_combine() to generate structured arrays instead of manual loops.
  • Initialize arrays before building them in loops.
  • Keep each array either a list or a map rather than mixing key styles.
  • Convert external data (strings, JSON) with the dedicated functions and validate the result. Official reference: https://www.php.net/manual/en/function.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 Create Arrays and get answers drawn from it.

Signed-in readers only.