Over a million developers have joined DZone.

Beyond Popular Array Functions in PHP [With Examples]

DZone 's Guide to

Beyond Popular Array Functions in PHP [With Examples]

In this post, you will see some extra features of PHP and get some secrets and tips that you can use in your code right away.

· Web Dev Zone ·
Free Resource

Image title

It was on a hot night several years ago when looking over notes from the previous morning's classes that I found out I had been assigned a very interesting homework.

The test that the computer science professor wanted me and my mates to do was to take a sentence of our choice (with at least a dozen words) and turn it into an array with the words itself instead of the elements.

Then make a copy of the array and create a new variable consisting of a string containing the words taken from the newly created array.

Finally, by writing a condition statement, verify that the two strings were the same and send a success or error message according to the result.

I still remember that after the first couple of hours experimenting with multiple variables creation, for...each cycles here and there and whatever else, I pulled the notepad on the wall and went to sleep.

Level of frustration: 100/100;

Keep in mind that I was still a student and the PHP language was a new thing for me.

The next day the same professor showed me that, to complete the exercise, it would have been enough to use the functions already built into the language and 3 lines would have been enough instead of the 600 that I was using.

This has changed my career forever, and I’m sure once you understand this, it will change yours too.

The principle here is: do not reinvent the wheel.

During the last few posts, we have seen that there are different categories of functions that PHP provides in order to work profitably with arrays and elements present within them.

If you are new here or have not followed the series, this series has been divided into several parts. In the first part, we saw what arrays are and how to best exploit them using the built-in functions within PHP. In the second part, we explored the most popular features of array function. In Part 3, we saw how to filter the elements of an array (which is one of the main functions used by the web developer) and finally how to sort array elements themselves.

In this post, you will see some extra features and some secrets and tips that you can use right away.

Most of these features are very easy to understand, others you will find as you continue your career in web development in PHP and its core packages.

The functions you will learn today are:

  • array_product() 

  • array_column()

  • explode()

  • implode()

  • array_sum()

  • array_product()

  • array_column()

  • compact()

  • extract()


This was the first function the professor taught me that day. There is absolutely no need to do multiple loops or use complex solutions in order to derive an array from a string. PHP provides this built-in function in its core and has been implemented to do this.

The explode()function has three parameters. The first two are mandatory, while the third one is not mandatory and, if I can be frank, not much used.

  1. The first parameter is the delimiter, as mentioned above in our case it will be composed of spaces.

  2. The second parameter is the string itself, nothing to say here.

  3. The third parameter is a bit more complex and consists of the limit. The limit can be positive, negative or zero. If negative, all components are returned except for the last one. If the limit indicated is 0, the limit considered will be one element. A positive limit, instead, returns an array containing a maximum number of elements equal to the specified number.

Now, what do we need when we want to create different elements from a string? We need the string and the elements that make it up.

Let’s take a look at this example:

“Hi Ho Hi Ho It’s Off To Work We Go”

This is the string, the elements that we need and that must be inserted inside the array are the words.

The simplest way to insert single words is through the use of delimiters, in this case, the spaces that separate the words.

The result of this function will be an array with 10 elements.

Let’s analyze how this string is structured:

Here is an example that uses the third parameter:

$str = "Hi Ho Hi Ho Its Off To Work We Go";
// With no limit
print_r(explode('', $str));
// With limit
print_r(explode('', $str, 2));
    [0] => Hi
    [1] => Ho
    [2] => Hi
    [3] => Ho
    [4] => Its
    [5] => Off
    [6] => To
    [7] => Work
    [8] => We
    [9] => Go
    [0] => Hi
    [1] => Ho Hi Ho Its Off To Work We Go

There are several factors that you need to consider when applying the explode() function. If the delimiter is composed of an empty string the function will return the value FALSE, if the delimiter is not present in the string and the limit indicated is negative the returned value will be an empty string.

You can find some other example of the explode function on W3schools


In the previous section, you saw how to get an array from a string, As you’ve already deduced, PHP allows you to do the opposite operation as well. By supplying an array to the implode() function you will get a string containing the values of the array elements.

Nothing could be simpler.

There are, however, some peculiarities to note.

Being a function that was initially published in PHP 4, it is not surprising that after all these years and different versions of the language the function has changed from what it was originally.

Let’s take a deeper look:

implode()has two attributes:

The first is officially called glue and consists of a string containing the set of characters or words that will separate the different elements of the array.

More unique than rare, even being the first parameter of the function, it is not a mandatory field,

It can, in fact, be omitted, and replaced by the second parameter of this function.

The second parameter of the function is the array. It will eventually be transformed into the string. Do you want to know a particularity? The array is not a mandatory field either. How is that possible? PHP allows you to invoke this function without specifying any parameters; the result will provide an empty string variable.

It may seem like a positive factor, but, as there is no mistake, you have to pay even more attention to the result obtained by the function. Here is an example:

$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'];
$string = implode(",", $dwarfs);
echo $string; // Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy


This function is a shortcut to a specific use that you can make of elements within the array. Suppose you have an array containing several numbers and you want to make the sum between them. The most logical reasoning would be to create aloop and sum the elements within a variable.

array_sum() performs exactly this operation, automatically and in a single line. It works with both numerical and associative arrays.

The values that this function considers are integers or floats, while the returned value is a numeric type value which can be 0 (if the array is empty) or the total sum of the elements.

$numbers = array(
    "first" => 11.4, 
    "second" => 4.1, 
    "third" => 8.9
echo array_sum($numbers); // 24.4

It can also be used to derive the average value of an array of numbers. Copy and paste the code below:

$average_of_numbers = array_sum($numbers) / count($numbers); // 8.13


array_product() is incredibly similar to array_sum().

Both the syntax and the conditions are the same as those indicated in the previous section.

The only difference between the two functions is that the final result of array_product() is the product of all the numbers present between the elements.

$numbers = array(2, 4, 6, 8); 
echo array_product($numbers); // 384

Curiosity: if the array selected as a parameter is an empty array, contrary to what you might think the value derived is not 0 or NULL but 1.

Here is a demonstration:

echo array_product([]); // 1


This function returns the values present in a column of an associative array supplied as a parameter.

array_column() comes from version 5.5 of PHP and uses three parameters, of which the first two are mandatory.

  1. The first parameter is the array from which we want to get the values.

  2. The second parameter consists of the name of the key of the array.

  3. Normally, the returned array is numeric but, indicating another of the other columns present within the selected array, the returned array will be of an associative type and will have the values of the third field as a key.

Given all the moving parts used by this function, it is not difficult to understand that its use can result in several errors.

In fact, it is a rather complex function and I advise you to always be attentive to the result provided and that there rae no errors or warning. 

$dwarfs = array(
       'id' => 1,
       'name' => 'Doc',
       'voice' => 'Roy Atwell'
       'id' => 2,
       'name' => 'Grumpy',
       'voice' => 'Pinto Colvig'
       'id' => 3,
       'name' => 'Happy',
       'voice' => 'Otis Harlan'
       'id' => 4,
       'name' => 'Sleepy',
       'voice' => 'Pinto Colvig'
       'id' => 5,
       'name' => 'Dopey',
       'voice' => 'Eddie Collins'
       'id' => 6,
       'name' => 'Bashful',
       'voice' => 'Scotty Mattraw'
       'id' => 7,
       'name' => 'Sneezy',
       'voice' => 'Billy Gilbert'
print_r(array_column($dwarfs, 'name', 'id'));
   1 => Doc
   2 => Grumpy
   3 => Happy
   4 => Sleepy
   5 => Dopey
   6 => Bashful
   7 => Sneezy


If you have ever used any of the PHP frameworks, surely you have already come across this function. If you have never used a PHP framework or want to have a look at what’s available in the market, I wrote an article in which I reviewed 24 of the most popular frameworks and interviewed the developers of some of them. 

compact() is widely used in order to create unique variables that can be sent to views in applications that use the MVC paradigm.

Some PHP frameworks have even modified this function to make it more suitable for their needs. Laravel uses the with() function, for example.

As said, this function creates a single variable of type array containing all the variables and the values inserted as parameters.

compact() examines the code and searches for all variables with the given name.

Here is a concrete example:

$name  = "Doc";
$voice = "Roy Atwell";
$movie = "Snow White and the Seven Dwarfs";
print_r(compact("movie", "empty_variable", array("name", "voice")));
    [movie] => Snow White and the Seven Dwarfs
    [name] => Doc
    [voice] => Roy Atwell


Let’s do some computer science.

In computer science, a symbol table is a data structure used by a linguistic translator, in the case of PHP an interpreter.

An interpreted language is a type of programming language.

Compiled vs. Interpreted Languages
Compiled vs. Interpreted Languages

The majority of its implementations execute instructions directly. There is no need to previously compile the code into machine-language instructions.

I explain more about it in the PHP Basic for experts series.

Each identifier, called a symbol, in a program’s source code is associated with information about its declaration. The symbol table stores information about the symbol. The extract() function imports the variables in the current symbol table from an array.

In other words, it produces exactly the opposite result of compact().

It has three parameters, two of which are not mandatory. The first parameter is the array, it must be of an associative type. The second parameter consists of one of the available flags, it indicates how the keys are treated in the case of invalid inputs.

There are several flags available:

  • EXTR_OVERWRITE - In the event of a collision, the function overwrites the existing variable. If no key is indicated, this flag will be the default value.

  • EXTR_SKIP - In the event of a collision, the function does not overwrite the existing variable.

  • EXTR_PREFIX_SAME - If there is a collision, enter prefix as the prefix of the variable name.

  • EXTR_PREFIX_ALL - It prefixes all variable names with a prefix.

  • EXTR_PREFIX_INVALID - It prefixes only the names of invalid or numeric variables with the prefix.

  • EXTR_IF_EXISTS - It overwrites the variable only if it already exists in the current symbol table, otherwise it will not perform any operation.

  • EXTR_PREFIX_IF_EXISTS - Creates variable names with a prefix only if the non-fixed version of the same variable is already present in the current symbol table.

  • EXTR_REFS - Extracts the variables as references. This means the variable values refer to the values of the array parameters.

You can use this flag alone or combine it with any other flag (use OR in this case).

You can take a more detailed look at these flags by using the official PHP manual.

The third parameter, also optional, is a string type variable and consists of the prefix with which the created variables will be named.

As with some of the functions already seen in this article, the array is taken as a reference, which translates into two meanings.

  1. The first is that the array itself is modified, not a variable returned from the array.

  2. The second is the variable returned by the function is of another type, in this case of type integer, and indicates the number of variables imported in the symbol table.

In a sense, this function works closely with the PHP interpreter, which means we need to pay more attention to the values to be used.

$name = "Doc";
$dwarf = array(
             "movie" => "Snow White and the Seven Dwarfs",
             "name"  => "Happy",
             "voice" => "Roy Atwell"
extract($dwarf, EXTR_PREFIX_SAME, "pre");
echo "$movie, $name, $voice, $pre_name";
// Snow White and the Seven Dwarfs, Doc, Roy Atwell, Happy

A phrase emphasized several times by both experienced developers and the PHP manual itself is that you don’t have to use extract() with an untrusted date as global variables, like $_GET or $_FILES. 

Conclusion of the Series

As with other series in my blog (head here to browse) we have reached the end of the path.

In this seriesm we have seen more than 50 functions that more or less directly involve arrays and their elements. We have gone from the basic functions to specific sectors, such as the ordering and filtering of elements.

Although some PHP frameworks now use collections instead of arrays, knowing how they work and how to best use them will not only make you understand this programming language but make you a better programmer, and this is invaluable at any stage of your career.

array filter ,php tutorial ,web dev ,php arrays

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}