Close this search box.
Close this search box.

Using Arrays

Creating an Array

The formal method of creating an array is to use the array() function. Its syntax is:

$list = array ('apples', 'bananas', 'oranges');

Arrays automatically begin their indexing at 0, unless otherwise specified. In that example—which doesn’t specify an index for the elements—the first item, apples, is automatically indexed at 0, the second item at 1, and the third at 2.

Adding Items to an Array

In PHP, once an array exists, you can add extra elements to the array with the assignment operator (the equals sign), in a way similar to how you assign a value to a string or a number. When doing so, you can specify the key of the added element or not specify it, but in either case, you must refer to the array with the square brackets. To add two items to the existing $list array, you’d write

$list[] = 'pears';
$list[] = 'tomatoes';

If you don’t specify the key, each element is appended to the existing array, indexed with the next sequential number. Assuming this is the same array from the preceding section, which was indexed at 1, 2, and 3, pears is now located at 4 and tomatoes at 5.

Formatting print_r() to be readable

When you wish to see the contents of any PHP array, typically you use the print_r() function.

This will print all the array contents in a very messy text block, without any line-breaks whatsoever, wich is quite difficult to read and browse trough.

Wouldn’t it be so much nicer to show the array contents split by line, clean and easy to read and browse., to find what you’re looking after? To do so, use this function instead.

function print_r_neat($array) {
    print("<pre>" . print_r($array, true) . "</pre>");

Learning Resources