AnyCompiler

Arrays

A PHP array literal is written with square brackets: [10, 20, 30]. Indexing is 0-based, like most languages on this site — $nums[0] is the first element. $nums[] = 40 (with nothing inside the brackets on the left) appends a new element at the next available integer key, PHP's push shorthand.

<?php
$nums = [10, 20, 30];
echo $nums[0], "\n";
$nums[] = 40;
print_r($nums);
echo count($nums), "\n";
sort($nums);
print_r($nums);
$rev = array_reverse($nums);
print_r($rev);
Output
10
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)
4
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)
Array
(
    [0] => 40
    [1] => 30
    [2] => 20
    [3] => 10
)

print_r() shows an array's full structure — every key and value — which is what you want while learning or debugging, as opposed to echo, which can't print an array directly at all. count() returns the number of elements; sort() sorts in place and re-indexes from 0; array_reverse() returns a new reversed array rather than mutating the original. Next: associative arrays — the exact same array type, keyed with => instead of auto-incrementing integers, which makes it PHP's single workhorse collection: one data structure that's both a list and a dictionary.

Practice exercise

Create $nums = [1, 2, 3], push 4 onto it with $nums[], then echo array_sum($nums).