Eric The Coder
Posted on January 17, 2022
Today you will learn array création and manipulation in PHP.
This PHP crash course is free and will be posted here on dev.to. I'll be releasing a new article/post every two days or so. To not miss anything, you can follow me on twitter: Follow @EricTheCoder_
First, here is a very common scenario in web development that will help you to understand why we need Array.
In the next exemple, we need to display a list of products and their prices.
$product1 = "iPad";
$product2 = "iPhone";
$product3 = "iWatch";
$price1 = 599;
$price2 = 899;
$price3 = 699;
echo $product1 . ' : ' . $price1 . '<br>';
echo $product2 . ' : ' . $price2 . '<br>';
echo $product3 . ' : ' . $price3 . '<br>';
As you can imagine, this code is far from optimal. Imagine if we had 100 products or even 10,000 products.
There is a way to do the previous exemple in a much more efficient way... Arrays.
Arrays in PHP are a lists of values. Values in an array can be of different type.
To define an array we use square brackets [ ]
$products = [];
The variable $products is an array
It is possible to create an array with content
$products = ['iPad', 'iPhone', 'iWatch'];
This array contains three strings: iPad, iPhone, iWatch
Each array element is separated by a comma.
It is possible to have arrays with different type of variable
$array = ['First entry', 100, true];
It is even possible to create an array within an array
$array = ['First entry', 100, ['iPad', 'iPhone'], false];
To access an item
echo $array[0];
// First entry
The elements of an array are indexed from 0. So the first item is at position 0, the second at position 1, and so on.
$array = ['First entry', 100, ['iPad', 'iPhone'], false];
0 1 2 3
To access an array within an array you use the following syntax
echo $array[2][1];
// iPhone
Here we display element 2, i.e. ['iPad', 'iPhone']
Then element 1 is iPhone
If you attempt to access a non-existent item. PHP will return a warning and the value null.
$array = ['First entry', 100, true];
echo $array[3];
// null
// Warning: Undefined array key 3
Count
To determine the number of items in an array you can use the count() function
$array = ['First entry', 100, true];
echo count($array);
// 3
Array manipulation
Add an element at the end of the array
$array[] = 'Last';
// ['First entry', 100, ['iPad', 'iPhone'], false, 'Last']
Remove an element from the array
unset($array[0]);
// [100, ['iPad', 'iPhone'], false, 'Last']
Convert an array to a string with the implode function
$array = ['One', 'Two', 'Three'];
echo implode(', ', $array);
// "One, Two, Three"
The first parameter is the separator.
Transform a string into an array with the explode function
$text = 'Mike, Shawn, John';
echo explode(',', $text); // ['Mike', 'Shawn', 'John'];
The first parameter is the separator.
Iterate through all elements of an array
The foreach function executes code for each element of the array.
$names = ['Mike', 'Shawn', 'John'];
foreach($names as $name) {
echo 'Hello ' . $name;
}
The first parameter is the name of the array to browse, the second parameter represents the reference to the current element.
Associative arrays
So far we have learned how arrays work. They have a number key starting from 0.
It is possible to create arrays with a custom key. This is what PHP calls associative arrays.
$person = ['age' => 45, 'genre' => 'men'];
Here 'age' and 'gender' are the keys. 45 and men are the values associated with these keys.
Note that some programming languages call this type of array a dictionary.
Associative arrays are very practical and you must understand them well because you will use them very often. They are perfect for storing information.
$product = ['id' => 100, 'name' => 'iPad', 'price' => 699];
Access to an array value is done with the key
echo "Product :" . $product['name'];
Adding a key/value to the array is possible by specifying a new key
$product['qty'] = 5;
It is possible to check if a key exists
$product = ['id' => 100, 'name' => 'iPad', 'price' => 699];
echo array_key_exists('id', $product);
// true
Loop in an associative array with values and keys
foreach($names as $key => $value) {
echo $key . ' : ' . $value;
}
Concatenation: Join two arrays
$names1 = ['Mike', 'Paul', 'Tom'];
$names2 = ['John', 'Sam'];
$allNames = array_merge($names1, $names2);
// ['Mike', 'Paul', 'Tom', 'John', 'Sam'];
Concatenation with the spread operator (...)
$names1 = ['Mike', 'Paul', 'Tom'];
$names2 = ['John', 'Sam'];
$allNames = [...$names1, ...$names2];
// ['Mike', 'Paul', 'Tom', 'John', 'Sam'];
Here, the spread operator before the array name (...$names) deconstructs the array.
An array of associative arrays
A pattern that you will use often is an array containing associative arrays.
$items = [
['id' => '100', 'name' => 'product 1'],
['id' => '200', 'name' => 'product 2'],
['id' => '300', 'name' => 'product 3'],
['id' => '400', 'name' => 'product 4'],
];
This kind of table is excellent for representing data.
It is possible to loop and display each item
foreach($items as $item) {
echo $item['name'] . <br>;
}
The 'as' statement create a reference to the array item.
Retrieve part of an array
There are several functions that allow you to retrieve part of an array.
Retrieve only keys or values
$person = ['age' => 45, 'genre' => 'men'];
// Return an array with only keys
echo array_keys($person); // ['age', 'genre']
// Return an array with only values
echo array_values($person); // [45, 'men']
Retrieval of items that match a specific criterion with the array_filter() function
$items = [
['id' => 100, 'name' => 'product 1'],
['id' => 200, 'name' => 'product 2'],
['id' => 300, 'name' => 'product 3'],
['id' => 400, 'name' => 'product 4'],
];
$filteredItem = array_filter($items, function ($product) {
return $product['id'] > 200;
});
print_r($filteredItem);
// $items = [
// ['id' => '300', 'name' => 'product 3'],
// ['id' => '400', 'name' => 'product 4'],
// ];
The array_filter() function is a function with a callback function as parameter. For each item in the array an expression will be evaluated. If the expression is true, the current item will be included in the resulting array.
Search in an array
$items = [
['id' => '100', 'name' => 'product 1'],
['id' => '200', 'name' => 'product 2'],
['id' => '300', 'name' => 'product 3'],
['id' => '400', 'name' => 'product 4'],
];
$found_key = array_search('product 3', array_column($items, 'name'));
// 2
The array_search() function allows you to search for a specific key according to a search criterion. In the last example we look for the key of 'product 3' in the 'name' column
Create a new array with the array_map() function
$items = [
['id' => 100, 'name' => 'product 1'],
['id' => 200, 'name' => 'product 2'],
['id' => 300, 'name' => 'product 3'],
['id' => 400, 'name' => 'product 4'],
];
$mapItems = array_map(function ($product) {
return [
'id' => $product['id'] * 2,
'name' => $product['name']
];
}, $items);
print_r($mapItems);
//[
['id' => 200, 'name' => 'product 1'],
['id' => 400, 'name' => 'product 2'],
['id' => 600, 'name' => 'product 3'],
['id' => 800, 'name' => 'product 4'],
];
The array_map() function returns an array that contains what each callback item will return.
The array_map() function must have two parameters: a callback function and an array. ex. array_map(callback function, arrays)
The array_map() function loops over each array item and at the same time builds a new array. Each item in the new array is the result (return) of the callback function. In the last example, each loop returned an item with the id * 2 and the product name.
The original table is not modified, a new table is created.
The array_reduce() function
This function takes an array and reduces it to a single value. Eg returned the result of adding all numbers contains in an array.
$numbers = [2, 4, 6, 100];
$sum = array_reduce($numbers, function ($num, $total) {
return $total + $num;
}, 0);
print_r($sum);
// 112
The array_reduce() function take two parameters: reference to actual item and a total variable. For each iteration, the callback function return the result in the total variable.
Conclusion
That's it for today, I'll be releasing a new article every two days or so. To be sure not to miss anything you can follow me on twitter: Follow @EricTheCoder_
Posted on January 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.