iDevie
December 2020
M T W T F S S
« Nov    
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories


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

There are two different ways of creating arrays. One is to use array() to specify the elements as key-value pairs. The other method is to put all elements inside []. There are two important points that you should remember when creating associate arrays with key pairs.

First, the key always has to be unique. If you try to use the same key multiple times in an array, PHP will ignore all other key-value pairs except the last one. Second, if a key is created as floats, bools, and valid string representations of integers, then it will be cast to integers.

Here are a few examples of creating arrays in PHP:

As you can see, using either array() or [] is equivalent when creating arrays. The shorthand notation has been available starting from PHP 5.4.

You also don’t need to specify a key for every array value. When left out, PHP sets the key to one more than the largest specified integer key. All automatically assigned keys will be greater than or equal to 0.

Working With Keys and Values

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:

You should know that the array_values() function returns an indexed array of values, array_keys() returns an array of keys of a given array, and array_flip() exchanges keys with values:

You can check if an array contains a specific value and get its first corresponding key using the array_search() function. You can also use in_array() if you just want to know whether an array contains a specific element and are not interested in its position. Consider using the array_key_exists() function when you want to check if the array uses a given key.

As the example above shows, make sure you use strict type checking if you don’t want any unexpected results.

If you want to look up multiple elements in an array, it’s usually faster to check if it contains a particular value by first flipping the array with array_flip() and then using array_key_exists().

Make Your Code Shorter

The list() function, which is not really a function but a language construction, is designed to assign variables in a short way. For example, here’s a basic example of using the list() function:

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:

Also, list() can be used with foreach, which makes this construction even better:

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:

Be aware that extract() is not safe if you are working with user data (like results of requests), so it’s 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:

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:

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:

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:

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:

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:

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:

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:

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 using 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 using a reference in a callback. Array keys can also be passed easily:

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:

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:

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():

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:

Generating Arrays

To generate an array with a given size and the same value, use array_fill():

To generate an array with a range of keys and values, like hours in the day or letters, use range():

To get a part of an array—for example, just the first three elements—use array_slice():

If you ever want to generate an associative array with different keys and the same value assigned to each key, you can simply use the array_fill_keys() function.

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

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():

To create an id to a title map from an array of models, we can use a combination of array_combine() and array_column():

To get the top three values of an array, we can use array_count_values()arsort(), and array_slice():

It’s easy to use array_sum() and array_map() to calculate the sum of order in a few rows:

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.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

 

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.


Comments 0
There are currently no comments.