In this tutorial, I am going to make a list of common php array functions with examples of usage and best practices. Every PHP developer must know how to use them and how to combine array functions to make code readable and short.
Also, there is a presentation with given code examples, so you can download it from the related links and show it to your colleagues to build a stronger team.
The Basics
Let‘s start with the basic functions that work with array keys and values. One of them is array_combine(), which creates an array using one array for keys and another for its values:
$keys = [‘sky‘, ‘grass‘, ‘orange‘]; $values = [‘blue‘, ‘green‘, ‘orange‘]; $array = array_combine($keys, $values); print_r($array); // Array // ( // [sky] => blue // [grass] => green // [orange] => orange // )
1 print_r(array_keys($array)); // [‘sky‘, ‘grass‘, ‘orange‘] 2 print_r(array_values($array)); // [‘blue‘, ‘green‘, ‘orange‘] 3 print_r(array_flip($array)); 4 5 // Array 6 // ( 7 // [blue] => sky 8 // [green] => grass 9 // [orange] => orange 10 // )
Make Your Code Shorter
The function list(), which is not really a function, but a language construction, is designed to assign variables in a short way. For example, here is a basic example of using the list()
function:
1 // define array 2 $array = [‘a‘, ‘b‘, ‘c‘]; 3 4 // without list() 5 $a = $array[0]; 6 $b = $array[1]; 7 $c = $array[2]; 8 9 // with list() 10 list($a, $b, $c) = $array;
This construction works perfectly with functions like preg_slit()
or explode()
. Also, you can skip some parameters, if you don‘t need them to be defined:
1 $string = ‘hello|wild|world‘; 2 list($hello, , $world) = explode(‘|‘, $string); 3 echo("$hello, $world"); // hello, world
Also, list()
can be used with foreach
, which makes this construction even better:
1 $arrays = [[1, 2], [3, 4], [5, 6]]; 2 3 foreach ($arrays as list($a, $b)) { 4 $c = $a + $b; 5 echo($c . ‘, ‘); // 3, 7, 11, 6 }
With the extract() function, you can export an associative array to variables. For every element of an array, a variable will be created with the name of a key and value as a value of the element:
1 $array = [ 2 ‘clothes‘ => ‘t-shirt‘, 3 ‘size‘ => ‘medium‘, 4 ‘color‘ => ‘blue‘, 5 ]; 6 7 extract($array); 8 9 echo("$clothes $size $color"); // t-shirt medium blue
Be aware that extract()
is not safe if you are working with user data (like results of requests), so it is better to use this function with the flags EXTR_IF_EXISTS
and EXTR_PREFIX_ALL
.
The opposite of the previous function is the compact() function, which makes an associative array from variables:
1 $clothes = ‘t-shirt‘; 2 $size = ‘medium‘; 3 $color = ‘blue‘; 4 5 $array = compact(‘clothes‘, ‘size‘, ‘color‘); 6 print_r($array); 7 8 // Array 9 // ( 10 // [clothes] => t-shirt 11 // [size] => medium 12 // [color] => blue 13 // )
Filtering Functions
There is a great function for array filtering, and it is called array_filter(). Pass the array as the first param and an anonymous function as the second param. Return true
in a callback function if you want to leave this element in the array, and false
if you don‘t:
1 $numbers = [20, -3, 50, -99, 55]; 2 3 $positive = array_filter($numbers, function($number) { 4 return $number > 0; 5 }); 6 7 print_r($positive); // [0 => 20, 2 => 50, 4 => 55]
There is a way to filter not only by the values. You can use ARRAY_FILTER_USE_KEY
or ARRAY_FILTER_USE_BOTH
as a third parameter to pass the key or both value and key to the callback function.
Also, you can call array_filter()
without a callback to remove all empty values:
1 $numbers = [-1, 0, 1]; 2 3 $not_empty = array_filter($numbers); 4 5 print_r($not_empty); // [0 => -1, 2 => 1]
You can get only unique values from an array using the array_unique() function. Notice that the function will preserve the keys of the first unique elements:
1 $array = [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 5]; 2 $uniques = array_unique($array); 3 4 print_r($uniques); 5 6 // Array 7 // ( 8 // [0] => 1 9 // [4] => 2 10 // [7] => 3 11 // [8] => 4 12 // [9] => 5 13 // )
With array_column(), you can get a list of column values from a multi-dimensional array, like an answer from a SQL database or an import from a CSV file. Just pass an array and column name:
1 $array = [ 2 [‘id‘ => 1, ‘title‘ => ‘tree‘], 3 [‘id‘ => 2, ‘title‘ => ‘sun‘], 4 [‘id‘ => 3, ‘title‘ => ‘cloud‘], 5 ]; 6 7 $ids = array_column($array, ‘id‘); 8 9 print_r($ids); // [1, 2, 3]
Starting from PHP 7, array_column()
becomes even more powerful, because it is now allowed to work with an array of objects. So working with an array of models just became easier:
$cinemas = Cinema::find()->all(); $cinema_ids = array_column($cinemas, ‘id‘); // php7 forever!
Walking Through the Arrays
Using array_map(), you can apply a callback to every element of an array. You can pass a function name or anonymous function to get a new array based on the given array:
1 $cities = [‘Berlin‘, ‘KYIV‘, ‘Amsterdam‘, ‘Riga‘]; 2 $aliases = array_map(‘strtolower‘, $cities); 3 4 print_r($aliases); // [‘berlin‘, ‘kyiv, ‘amsterdam‘, ‘riga‘] 5 6 $numbers = [1, -2, 3, -4, 5]; 7 $squares = array_map(function($number) { 8 return $number ** 2; 9 }, $numbers); 10 11 print_r($squares); // [1, 4, 9, 16, 25]
There is a myth that there is no way to pass values and keys of an array to a callback, but we can bust it:
1 $model = [‘id‘ => 7, ‘name‘=>‘James‘]; 2 3 $callback = function($key, $value) { 4 return "$key is $value"; 5 }; 6 7 $res = array_map($callback, array_keys($model), $model); 8 print_r($res); 9 10 // Array 11 // ( 12 // [0] => id is 7 13 // [1] => name is James 14 // )
But this looks dirty. It is better to use array_walk() instead. This function looks the same as array_map()
, but it works differently. First of all, an array is passed by a reference, so array_walk()
doesn‘t create a new array, but changes a given array. So as a source array, you can pass the array value by a reference in a callback. Array keys can also be passed easily:
1 $fruits = [ 2 ‘banana‘ => ‘yellow‘, 3 ‘apple‘ => ‘green‘, 4 ‘orange‘ => ‘orange‘, 5 ]; 6 7 array_walk($fruits, function(&$value, $key) { 8 $value = "$key is $value"; 9 }); 10 11 print_r($fruits); 12 13 // Array 14 // ( 15 // [banana] => banana is yellow 16 // [apple] => apple is green 17 // [orange] => orange is orange 18 // )
Joining the Arrays
The best way to merge two or more arrays in PHP is to use the array_merge() function. Items of arrays will be merged together, and values with the same string keys will be overwritten with the last value:
1 $array1 = [‘a‘ => ‘a‘, ‘b‘ => ‘b‘, ‘c‘ => ‘c‘]; 2 $array2 = [‘a‘ => ‘A‘, ‘b‘ => ‘B‘, ‘D‘ => ‘D‘]; 3 4 $merge = array_merge($array1, $array2); 5 print_r($merge); 6 // Array 7 // ( 8 // [a] => A 9 // [b] => B 10 // [c] => c 11 // [D] => D 12 // )
To remove array values from another array (or arrays), use array_diff(). To get values which are present in given arrays, use array_intersect(). The next examples will show how it works:
1 $array1 = [1, 2, 3, 4]; 2 $array2 = [3, 4, 5, 6]; 3 4 $diff = array_diff($array1, $array2); 5 print_r($diff); // [0 => 1, 1 => 2] 6 7 $intersect = array_intersect($array1, $array2); 8 print_r($intersect); // [2 => 3, 3 => 4]
Do the Math With Array Values
Use array_sum() to get a sum of array values, array_product() to multiply them, or create your own formula with array_reduce():
1 $numbers = [1, 2, 3, 4, 5]; 2 3 echo(array_sum($numbers)); // 15 4 echo(array_product($numbers)); // 120 5 6 echo(array_reduce($numbers, function($carry, $item) { 7 return $carry ? $carry / $item : 1; 8 })); // 0.0083 = 1/2/3/4/5
To count all the values of an array, use array_count_values(). It will give all unique values of a given array as keys and a count of these values as a value:
1 $things = [‘apple‘, ‘apple‘, ‘banana‘, ‘tree‘, ‘tree‘, ‘tree‘]; 2 $values = array_count_values($things); 3 4 print_r($values); 5 6 // Array 7 // ( 8 // [apple] => 2 9 // [banana] => 1 10 // [tree] => 3 11 // )
Generating Arrays
To generate an array with a given size and the same value, use array_fill():
1 $bind = array_fill(0, 5, ‘?‘); 2 print_r($bind); // [‘?‘, ‘?‘, ‘?‘, ‘?‘, ‘?‘]
To generate an array with a range in of keys and values, like day hours or letters, use range():
1 $letters = range(‘a‘, ‘z‘); 2 print_r($letters); // [‘a‘, ‘b‘, ..., ‘z‘] 3 4 $hours = range(0, 23); 5 print_r($hours); // [0, 1, 2, ..., 23]
To get a part of an array—for example, just the first three elements—use array_slice():
1 $numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 2 $top = array_slice($numbers, 0, 3); 3 print_r($top); // [1, 2, 3]
Sorting Arrays
It is good to remember that every sorting function in PHP works with arrays by a reference and returns true on success or false on failure. There‘s a basic sorting function called sort(), and it sorts values in ascending order without preserving keys. The sorting function can be prepended by the following letters:
- a, sort preserving keys
- k, sort by keys
- r, sort in reverse/descending order
- u, sort with a user function
You can see the combinations of these letters in the following table:
a | k | r | u | |
a | asort | arsort | uasort | |
k | ksort | krsort | ||
r | arsort | krsort | rsort | |
u | uasort | usort |
Combining Array Functions Like a Boss
Combining Array Functions Like a Boss
The real magic begins when you start to combine array functions. Here is how you can trim and remove empty values in just a single line of code with array_filter()
and array_map()
:
1 $values = [‘say ‘, ‘ bye‘, ‘ ‘, ‘ to‘, ‘ spaces ‘, ‘ ‘]; 2 3 $words = array_filter(array_map(‘trim‘, $values)); 4 print_r($words); // [‘say‘, ‘bye‘, ‘to‘, ‘spaces‘]
To create an id to a title map from an array of models, we can use a combination of array_combine()
and array_column()
:
1 $models = [$model1, $model2, $model3]; 2 3 $id_to_title = array_combine( 4 array_column($models, ‘id‘), 5 array_column($models, ‘title‘) 6 );
To get the top three values of an array, we can use array_count_values()
, arsort()
, and array_slice()
:
1 $letters = [‘a‘, ‘a‘, ‘a‘, ‘a‘, ‘b‘, ‘b‘, ‘c‘, ‘d‘, ‘d‘, ‘d‘, ‘d‘, ‘d‘]; 2 3 $values = array_count_values($letters); // get key to count array 4 arsort($values); // sort descending preserving key 5 $top = array_slice($values, 0, 3); // get top 3 6 7 print_r($top); 8 // Array 9 // ( 10 // [d] => 5 11 // [a] => 4 12 // [b] => 2 13 // )
array_sum()
and array_map()
to calculate the sum of order in a few rows:1 $order = [ 2 [‘product_id‘ => 1, ‘price‘ => 99, ‘count‘ => 1], 3 [‘product_id‘ => 2, ‘price‘ => 50, ‘count‘ => 2], 4 [‘product_id‘ => 2, ‘price‘ => 17, ‘count‘ => 3], 5 ]; 6 7 $sum = array_sum(array_map(function($product_row) { 8 return $product_row[‘price‘] * $product_row[‘count‘]; 9 }, $order)); 10 11 print_r($sum); // 250
Advertisement
Conclusion
As you can see, knowledge of the main array functions can make your code much shorter and more readable. Of course, PHP has many more array functions, and even the given functions have many variations to use with extra parameters and flags, but I think that in this tutorial we‘ve covered the basics that every PHP developer should know.
Please note that I‘ve created a presentation with the given examples, so you can download it from the related links and show it to your team.
If you have any questions, don‘t hesitate to ask them in the comments to the article.