Arrays

If you have some experience with other programming languages or data structures in general, you might be aware of two data structures that are very common and useful: lists and maps. A list is an ordered set of elements, whereas a map is a set of elements identified by keys. Let's see an example:

List: ["Harry", "Ron", "Hermione"]

Map: {
  "name": "James Potter",
  "status": "dead"
}

The first element is a list of names that contains three values: Harry, Ron, and Hermione. The second one is a map, and it defines two values: James Potter and dead. Each of these two values is identified with a key: name and status respectively.

In PHP, we do not have lists and maps; we have arrays. An array is a data structure that implements both, a list and a map.

Initializing arrays

You have different options for initializing an array. You can initialize an empty array, or you can initialize an array with data. There are different ways of writing the same data with arrays too. Let's see some examples:

<?php
$empty1 = [];
$empty2 = array();
$names1 = ['Harry', 'Ron', 'Hermione'];
$names2 = array('Harry', 'Ron', 'Hermione');
$status1 = [
    'name' => 'James Potter',
    'status' => 'dead'
];
$status2 = array(
    'name' => 'James Potter',
    'status' => 'dead'
);

In the preceding example, we define the list and map from the previous section. $names1 and $names2 are exactly the same array, just using a different notation. The same happens with $status1 and $status2. Finally, $empty1 and $empty2 are two ways of creating an empty array.

Later you will see that lists are handled like maps. Internally, the array $names1 is a map, and its keys are ordered numbers. In this case, another initialization for $names1 that leads to the same array could be as follows:

$names1 = [
    0 => 'Harry',
    1 => 'Ron',
    2 => 'Hermione'
];

Keys of an array can be any alphanumeric value, like strings or numbers. Values of an array can be anything: strings, numbers, Booleans, other arrays, and so on. You could have something like the following:

<?php
$books = [
    '1984' => [
        'author' => 'George Orwell',
        'finished' => true,
        'rate' => 9.5
    ],
    'Romeo and Juliet' => [
        'author' => 'William Shakespeare',
        'finished' => false
    ]
];

This array is a list that contains two arrays—maps. Each map contains different values like strings, doubles, and Booleans.

Populating arrays

Arrays are not immutable, that is, they can change after being initialized. You can change the content of an array either by treating it as a map or as a list. Treating it as a map means that you specify the key that you want to override, whereas treating it as a list means appending another element to the end of the array:

<?php
$names = ['Harry', 'Ron', 'Hermione'];
$status = [
    'name' => 'James Potter',
    'status' => 'dead'
];
$names[] = 'Neville';
$status['age'] = 32;
print_r($names, $status);

In the preceding example, the first highlighted line appends the name Neville to the list of names, hence the list will look like ['Harry', 'Ron', 'Hermione', 'Neville']. The second change actually adds a new key-value to the array. You can check the result from your browser by using the function print_r. It does something similar to var_dump, just without the type and size of each value.

Note

print_r and var_dump in a browser

When printing the content of an array, it is useful to see one key-value per line, but if you check your browser, you will see that it displays the whole array in one line. That happens because what the browser tries to display is HTML, and it ignores new lines or whitespaces. To check the content of the array as PHP wants you to see it, check the source code of the page—you will see the option by right-clicking on the page.

If you need to remove an element from the array, instead of adding or updating one, you can use the unset function:

<?php
$status = [
    'name' => 'James Potter',
    'status' => 'dead'
];
unset($status['status']);
print_r ($status);

The new $status array contains the key name only.

Accessing arrays

Accessing an array is as easy as specifying the key as when you were updating it. For that, you need to understand how lists work. You already know that lists are treated internally as a map with numeric keys in order. The first key is always 0; so, an array with n elements will have keys from 0 to n-1.

You can add any key to a given array, even if it previously consisted of numeric entries. The problem arises when adding numeric keys, and later, you try to append an element to the array. What do you think will happen?

<?php
$names = ['Harry', 'Ron', 'Hermione'];
$names['badguy'] = 'Voldemort';
$names[8] = 'Snape';
$names[] = 'McGonagall';
print_r($names);

The result of that last piece of code is as follows:

Array
(
    [0] => Harry
    [1] => Ron
    [2] => Hermione
    [badguy] => Voldemort
    [8] => Snape
    [9] => McGonagall
)

When trying to append a value, PHP inserts it after the last numeric key, in this case 8.

You might've already figured it out by yourself, but you can always print any part of the array by specifying its key:

<?php
$names = ['Harry', 'Ron', 'Hermione'];
print_r($names[1]); // prints 'Ron'

Finally, trying to access a key that does not exist in an array will return you a null and throw a notice, as PHP identifies that you are doing something wrong in your code.

<?php
$names = ['Harry', 'Ron', 'Hermione'];
var_dump($names[4]); // null and a PHP notice

The empty and isset functions

There are two useful functions for enquiring about the content of an array. If you want to know if an array contains any element at all, you can ask if it is empty with the empty function. That function actually works with strings too, an empty string being a string with no characters (' '). The isset function takes an array position, and returns true or false depending on whether that position exists or not:

<?php
$string = '';
$array = [];
$names = ['Harry', 'Ron', 'Hermione'];
var_dump(empty($string)); // true
var_dump(empty($array)); // true
var_dump(empty($names)); // false
var_dump(isset($names[2])); // true
var_dump(isset($names[3])); // false

In the preceding example, we can see that an array with no elements or a string with no characters will return true when asked if it is empty, and false otherwise. When we use isset($names[2]) to check if the position 2 of the array exists, we get true, as there is a value for that key: Hermione. Finally, isset($names[3]) evaluates to false as the key 3 does not exist in that array.

Searching for elements in an array

Probably, one of the most used functions with arrays is in_array. This function takes two values, the value that you want to search for and the array. The function returns true if the value is in the array and false otherwise. This is very useful, because a lot of times what you want to know from a list or a map is if it contains an element, rather than knowing that it does or its location.

Even more useful sometimes is array_search. This function works in the same way except that instead of returning a Boolean, it returns the key where the value is found, or false otherwise. Let's see both functions:

<?php
$names = ['Harry', 'Ron', 'Hermione'];
$containsHermione = in_array('Hermione', $names);
var_dump($containsHermione); // true
$containsSnape = in_array('Snape', $names);
var_dump($containsSnape); // false
$wheresRon = array_search('Ron', $names);
var_dump($wheresRon); // 1
$wheresVoldemort = array_search('Voldemort', $names);
var_dump($wheresVoldemort); // false

Ordering arrays

An array can be sorted in different ways, so there are a lot of chances that the order that you need is different from the current one. By default, the array is sorted by the order in which the elements were added to it, but you can sort an array by its key or by its value, both ascending and descending. Furthermore, when sorting an array by its values, you can choose to preserve their keys or to generate new ones as a list.

There is a complete list of these functions on the official documentation website at http://php.net/manual/en/array.sorting.php, but here we will display the most important ones:

Name

Sorts by

Maintains key association

Order of sort

sort

Value

No

Low to high

rsort

Value

No

High to low

asort

Value

Yes

Low to high

arsort

Value

Yes

High to low

ksort

Key

Yes

Low to high

krsort

Key

Yes

High to low

These functions always take one argument, the array, and they do not return anything. Instead, they directly sort the array we pass to them. Let's see some of them:

<?php
$properties = [
    'firstname' => 'Tom',
    'surname' => 'Riddle',
    'house' => 'Slytherin'
];
$properties1 = $properties2 = $properties3 = $properties;
sort($properties1);
var_dump($properties1);
asort($properties3);
var_dump($properties3);
ksort($properties2);
var_dump($properties2);

Okay, there is a lot going on in the last example. First of all, we initialize an array with some key values and assign it to $properties. Then we create three variables that are copies of the original array—the syntax should be intuitive. Why do we do that? Because if we sort the original array, we will not have the original content any more. This is not what we want in this specific example, as we want to see how the different sort functions affect the same array. Finally, we perform three different sorts, and print each of the results. The browser should show you something like the following:

array(3) {
  [0]=>
  string(6) "Riddle"
  [1]=>
  string(9) "Slytherin"
  [2]=>
  string(3) "Tom"
}
array(3) {
  ["surname"]=>
  string(6) "Riddle"
  ["house"]=>
  string(9) "Slytherin"
  ["firstname"]=>
  string(3) "Tom"
}
array(3) {
  ["firstname"]=>
  string(3) "Tom"
  ["house"]=>
  string(9) "Slytherin"
  ["surname"]=>
  string(6) "Riddle"
}

The first function, sort, orders the values alphabetically. Also, if you check the keys, now they are numeric as in a list, instead of the original keys. Instead, asort orders the values in the same way, but keeps the association of key-values. Finally, ksort orders the elements by their keys, alphabetically.

Tip

How to remember so many function names

PHP has a lot of function helpers that will save you from writing customized functions by yourself, for example, it provides you with up to 13 different sorting functions. And you can always rely on the official documentation. But, of course, you would like to write code without going back and forth from the docs. So, here are some tips to remember what each sorting function does:

  • An a in the name means associative, and thus, will preserve the key-value association.
  • An r in the name means reverse, so the order will be from high to low.
  • A k means key, so the sorting will be based on the keys instead of the values.

Other array functions

There are around 80 different functions related to arrays. As you can imagine, you will never even hear about some of them, as they have very specific purposes. The complete list can be found at http://php.net/manual/en/book.array.php.

We can get a list of the keys of the array with array_keys, and a list of its values with array_values:

<?php
$properties = [
    'firstname' => 'Tom',
    'surname' => 'Riddle',
    'house' => 'Slytherin'
];
$keys = array_keys($properties);
var_dump($keys);
$values = array_values($properties);
var_dump($values);

We can get the number of elements in an array with the count function:

<?php
$names = ['Harry', 'Ron', 'Hermione'];
$size = count($names);
var_dump($size); // 3

And we can merge two or more arrays into one with array_merge:

<?php
$good = ['Harry', 'Ron', 'Hermione'];
$bad = ['Dudley', 'Vernon', 'Petunia'];
$all = array_merge($good, $bad);
var_dump($all);

The last example will print the following array:

array(6) {
  [0]=>
  string(5) "Harry"
  [1]=>
  string(3) "Ron"
  [2]=>
  string(8) "Hermione"
  [3]=>
  string(6) "Dudley"
  [4]=>
  string(6) "Vernon"
  [5]=>
  string(7) "Petunia"
}

As you can see, the keys of the second array are now different, as originally, both the arrays had the same numeric keys, and an array cannot have two values for the same key.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.123.34