Create Arrays
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
| Function | Creates | Example |
|---|---|---|
range($start, $end, $step) | A sequence of numbers or letters | range(1, 5) |
array_fill($startIndex, $count, $value) | $count copies of a value | array_fill(0, 3, 'TBD') |
array_fill_keys($keys, $value) | Given keys, all with the same value | array_fill_keys(['a', 'b'], 0) |
array_combine($keys, $values) | Keys from one array, values from another | array_combine(['IN'], ['India']) |
array_pad($array, $size, $value) | An array extended to a given size | array_pad([1, 2], 5, 0) |
explode($separator, $string) | Pieces of a string | explode(',', 'a,b,c') |
str_split($string, $length) | Fixed-size chunks of a string | str_split('ABCDEF', 2) |
compact('var1', 'var2') | An array from existing variables | compact('name', 'city') |
json_decode($json, true) | An array from JSON | json_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 to0for 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 aValueError.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
range('A', 'C')creates the row letters['A', 'B', 'C'].array_fill(1, 4, 'free')creates one row of seats numbered 1 to 4 (seat numbers start at 1, as people expect).array_fill_keys()gives each row letter its own copy of that row, producing a two-level array.- Individual seats are updated with two keys:
$seats['B'][2]. - For display,
array_map()converts statuses to symbols. 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(), andarray_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