Arrays in PHP

Our first example demonstrates the use of arrays in PHP. In PHP, an array is an ordered map that can be used as an array, list, hash table, dictionary, collection, stack, queue, and more.

<?php

// Here we create an array $a that will hold 5 integers.
// By default, PHP arrays are zero-indexed.
$a = array_fill(0, 5, 0);
echo "emp: " . json_encode($a) . "\n";

// We can set a value at an index using the
// array[index] = value syntax, and get a value with
// array[index].
$a[4] = 100;
echo "set: " . json_encode($a) . "\n";
echo "get: " . $a[4] . "\n";

// The count() function returns the length of an array.
echo "len: " . count($a) . "\n";

// Use this syntax to declare and initialize an array
// in one line.
$b = [1, 2, 3, 4, 5];
echo "dcl: " . json_encode($b) . "\n";

// In PHP, you don't need to specify the size of the array
// when initializing it. It will automatically adjust.
$b = [1, 2, 3, 4, 5];
echo "dcl: " . json_encode($b) . "\n";

// PHP doesn't have a direct equivalent to Go's index-based
// initialization, but we can achieve a similar result:
$b = array_fill(0, 5, 0);
$b[0] = 100;
$b[3] = 400;
$b[4] = 500;
echo "idx: " . json_encode($b) . "\n";

// Array types in PHP are flexible and can hold different types.
// Here's an example of a 2D array:
$twoD = array(
    array(0, 1, 2),
    array(1, 2, 3)
);
echo "2d: " . json_encode($twoD) . "\n";

// You can also create and initialize multi-dimensional
// arrays at once.
$twoD = [
    [1, 2, 3],
    [1, 2, 3]
];
echo "2d: " . json_encode($twoD) . "\n";

When you run this program, you’ll see:

emp: [0,0,0,0,0]
set: [0,0,0,0,100]
get: 100
len: 5
dcl: [1,2,3,4,5]
dcl: [1,2,3,4,5]
idx: [100,0,0,400,500]
2d: [[0,1,2],[1,2,3]]
2d: [[1,2,3],[1,2,3]]

Note that arrays in PHP are much more flexible than in some other languages. They can dynamically grow and shrink, and can contain elements of different types. The json_encode() function is used here to display the arrays in a similar format to the Go example.

PHP arrays are actually ordered maps, which means they can also be used as dictionaries or hash tables. This makes them very versatile and powerful, but it’s important to keep in mind that they may behave differently from arrays in other languages in some situations.