1. Types of Arrays
2. Creating an Array
3. Accessing Elements
4. Array Operators
5. Retrieving the Lengt...
7. Adding/Removing Elem...
Having looked intensively at the four scalar data types, it’s time to move on to compound types; arrays and objects.
An array is nothing more than a list of values.
They are incredibly useful for grouping huge amounts of related data. Once saved inside an array, you can perform all sorts of operations on it - such as sorting or combining the data. For example, I could retrieve all the usernames of users that are currently in a chat room, put them inside an array, sort them alphabetically, and then display them to all other users with some HTML markup around them.
The values of an array are called its elements.
Types of Arrays
There are many types of lists in the real world – grocery lists, step-by-step lists, definition-explanation lists – which means we need versatile arrays. That’s why PHP arrays can, unlike some other programming languages, store values of different data type. For example, some elements can be integers while others are strings.
Additionally, we need to be able to retrieve the value of an element by accessing its key. For example, we could save a value “5 dollars” under the key “price”. There are three different types of arrays, based on how they use these key-value pairs:
- Indexed Arrays: The key of an element is a numeric index. Just as with strings, the first element of the array has index 0, the next one has index 1, and so on.
- Associative Arrays: The key of an element is a string or integer. In this case, the keys can be anything you like. (But they can’t be other data types, such as float or Boolean.)
- Multidimensional Arrays: The values are arrays! By placing an array inside an array, we basically create a table with rows and columns of data. (And, by adding even more arrays, we could make it three-dimensional and higher.) But, all of this is advanced stuff that will be discussed later.
Creating an Array
Arrays are flexible. Based on what syntax you use to define its elements, the array changes its type for you. To create an indexed array, use one of the following two syntaxes
array(value1, …, valuen); [value1, …, valuen];
This could only create an indexed array, because we’ve only provided values and no keys.
To create an associative array, use one of these two syntaxes
array(key1 => value1, …, keyn => valuen); [key1 => value1, …, keyn => valuen];
$shopping_cart = ["Bicycle", "Plush Toy", "Table Tennis Table"]; print_r($shopping_cart); /* Prints: Array (  => Bicycle  => Plush Toy  => Table Tennis Table ) */ $bicycle_info = ["price" => 10, "colour" => "red", "gears" => 5, "forsale" => true]; print_r($bicycle_info); /* Prints: Array ( [price] => 10 [colour] => red [gears] => 5 [forsale] => 1 ) */
PHP will automatically try to cast strings to integers, if possible, because indexed arrays are easier and faster to handle than associative ones. So, don’t add numbers enclosed in quotes as keys (like
"1"), because they will be converted to numeric indexes – and you will be confused.
We’ve now seen how to set an array’s values when you define it, but what if we want to add/remove or get/set a value later on? We can use the bracket-syntax – which we also used for accessing characters of a string – to refer to a single element of the array:
Note that this key can be an integer index, or a string – the syntax is the same. Also note that we can use the assignment operator (just as we would with variables) to assign a new value.
$shopping_cart = ["Bicycle", "Plush Toy", "Table Tennis Table"]; echo $shopping_cart; //Prints: Plush Toy
When you assign a value to a key that doesn’t exist within the array, PHP will be nice and add this new key-value pair to the array for you. On the other hand, to remove an element, you need to use
unset() again (just as with regular variables).
$shopping_cart = ["Bicycle", "Plush Toy", "Table Tennis Table"]; echo $shopping_cart; //Prints error that no element exists with index 5 $shopping_cart = "Laptop"; echo $shopping_cart; //Prints Laptop unset($shopping_cart); //Now it's been removed from the array again
Arrays, just like the other datatypes, support operators as well. Because it’s a list of things, however, they change their meaning if both operands are arrays. If only one operand is an array, these will throw an error.
Combines two arrays, and removes duplicate elements
Returns true if both arrays have the same key/value pairs
Returns true if both arrays have the same key/value pairs, in the same order, and of the same data type
Returns true if both arrays don’t have the exact same key/value pairs
Returns true if both arrays don’t have the exact same key/value pairs, or in a different order, or values of different data types
$user_login = ["usn" => "Ginty", "pwd" => "1234"]; $user_profile = ["pet" => "Panda", "gender" => "Girl"]; $user = $user_login + $user_profile; //Contains all information on the user $user_login_1 = ["usn" => "Ginty", "pwd" => "1234"]; $user_login_2 = ["pwd" => "1234", "usn" => "Ginty"]; //Prints bool(false), because key-value pairs are exactly the same var_dump($user_login_1 <> $user_login_2); //Prints bool(true), because the order is different var_dump($user_login_1 !== $user_login_2);
Even though it’s not possible to cast an array onto some other type, it is possible to cast scalar types to arrays. The result will be an array with a single element at index 0, with the scalar as its value.
Retrieving the Length
You’ll be retrieving the length of an array quite often, because you either want to display how many items are in a list, or want to go through all the elements of the array. (Which we’ll discuss in the chapters on Loops.) To do so, use one of these:
They do exactly the same (they are called aliases) – just pick the one you’re most likely to remember. Also keep in mind that, in the case of indexed arrays, the last element of the array has index (length-1), because we start counting from 0.
$users = ["Ginty", "Juan", "Mark", "Avocado", "BATMAN"]; echo sizeof($users); //Prints 5
Just as we could explode a string into an array, we can glue all the elements of an array together into a string. To do so, use one of these (again, they do exactly the same):
implode(separator, $array); join(separator, $array);
//Suppose we want to thank all our users for their contribution in a single sentence $users = ["Ginty", "Juan", "Mark", "Avocado", "BATMAN"]; echo "Thanks to " . implode(", ", $users) . "!"; //Prints Thanks to Ginty, Juan, Mark, Avocado, Batman!
For the quizzing system on this website, I dynamically create an array full of random, wrong answers and one right answer I fetch from my question database. It would be a pain to have to shift all the current elements one position to the right so I can add a new one at the start. Fortunately, PHP has some nice methods for adding/removing elements from the start/end of arrays.
To add elements at the start of the array (and therefore shift all the other elements one position to the right), use
array_unshift($array, value1, …, valuen);
To add elements at the end of an array, use
array_push($array, value1, …, valuen);
To remove the first element of an array (and therefore shift all the other elements one position to the left), use
To remove the last element of an array, use
$users_in_chatroom = ["Ginty", "Juan", "Mark", "Avocado", "BATMAN"]; //Hey, Laura just came into the chatroom! array_push($users_in_chatroom, "Laura"); //But, Ginty hates Laura, so she leaves array_shift($users_in_chatroom); //Now Laura is upset as well, so she leaves array_pop($users_in_chatroom); /*Now the array is Array (  => Juan  => Mark  => Avocado  => BATMAN ) */