Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Arrays

An array holds several values under one name: a list of products, a user's data, table rows. It is the most widely used data structure in PHP.

A list

The simplest array is a list of values in square brackets. Every element has a number, or index, and counting starts from zero:

<?php
 
$colors = ['red', 'green', 'blue'];
 
echo $colors[0]; // red

Number of elements

count() returns the number of elements in an array:

<?php
 
$colors = ['red', 'green', 'blue'];
 
echo count($colors); // 3

The index of the last element is always one less than the count.

Adding and changing

Empty square brackets append an element, and an index replaces an existing one:

<?php
 
$colors = ['red', 'green', 'blue'];
 
$colors[] = 'yellow';
$colors[0] = 'white';
 
echo implode(', ', $colors); // white, green, blue, yellow

implode() joins the elements of an array into a string using the given separator.

Associative arrays

Instead of numbers you can use your own keys, usually strings. Such an array is handy for describing a single object:

<?php
 
$user = [
    'name' => 'Anna',
    'age' => 25,
];
 
echo $user['name']; // Anna

Iterating

foreach can give you the key as well as the value:

<?php
 
$user = ['name' => 'Anna', 'age' => 25];
 
foreach ($user as $key => $value) {
    echo "$key: $value\n";
}

Useful functions

<?php
 
$numbers = [3, 1, 2];
 
sort($numbers);
 
echo implode(', ', $numbers), "\n"; // 1, 2, 3
echo array_sum($numbers), "\n";     // 6
var_dump(in_array(2, $numbers));    // bool(true)

sort() reorders the array itself instead of returning a new one. in_array() checks whether a value is among the elements.

A common mistake

Reading a key that does not exist triggers an Undefined array key warning. If a key may be missing, supply a default with ??:

<?php
 
$user = ['name' => 'Anna'];
 
echo $user['city'] ?? 'not set'; // not set

Thanks for reading!

Donate to the site — we work hard for you.