DEV Community

Cover image for Array function in PHP
anastasionico
anastasionico

Posted on • Updated on

Array function in PHP

In the first part of this series, you saw some of the most used array functions that the PHP language makes available,

Fortunately, after years and years of evolution and the publication of new versions of the language this list of array functions is still long, it almost seems that it never ends.

Let's take a look at other array functions , those in the list below are a little less common but here is where you become an expert in the PHP language.

About the series

This blog post that belongs to the series " PHP array exposed".

If you haven't already read the other articles

have a look at them:

PHP array Exposed (part one)

Creation and Manipulation of Arrays

array_reverse()

The array_reverse() function is a fun one and at the same time very useful and incredibly easy to use.

array_reverse() in fact, takes an array as the first and only mandatory parameter and reverses the order of the elements within the given array.

This function also has another parameter, optional in this case which consists of a variable of type bool, if the second parameter is true the numeric keys will be kept if instead the parameter is false or the parameter is not supplied the order will be arranged according to the elements present in the array.

Note that if the keys are not numeric they will always be saved and the second parameter will have no effect on them.

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
$sfrawd = array_reverse($dwarfs); 
print_r($sfrawd); 
Array ( 
    [0] => Sneezy 
    [1] => Bashful 
    [2] => Dopey 
    [3] => Sleepy 
    [4] => Happy 
    [5] => Grumpy 
    [6] => Doc )

 

array_flip()

The array_flip function takes an array as a parameter and returns an array in which it exchanged keys for values , it can be seen as an original way to get the keys of an array or for dozens of different goals.

This function also has several limitations, for example, the keys must follow the precise type , as ordered from PHP the key can only be integer or string otherwise you will receive a warning and the function won't work.

Another feature you need to pay attention to is the number of identical keys, in fact, only the last one among them will be used and all the others will be lost.

 

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
$flipped = array_flip($dwarfs); 
Array ( 
    [Doc] => 0 
    [Grumpy] => 1 
    [Happy] => 2 
    [Sleepy] => 3 
    [Dopey] => 4 
    [Bashful] => 5 
    [Sneezy] => 6 )

Here are other examples about array_flip

array_rand()

Admittedly the function array_rand() is in a bit strange and if you decide to use it you have to pay attention that the result you want to obtain is in the chosen format.

This function can indeed return an array, an integer or even a string.

The job of array_rand() is to take and return one or more keys from elements present within an array.

Having been inserted in PHP 4, This function is quite old, but it has been modified several times since then.

From PHP 7.1, for example, array_rand() uses a new algorithm called Mersenne Twister to generate its numbers.

Although this algorithm randomly takes the numbers it is not suitable for cryptographic purposes.

$dwarfs = array( 
    'zero' => 'Doc', 
    'first' => 'Grumpy', 
    'second' => 'Happy', 
    'third' => 'Sleepy', 
    'fourth' => 'Dopey', 
    'fifth' => 'Bashful', 
    'sixth' => 'Sneezy' 
);

print_r(array_rand($dwarfs, 1)); 
'Second' print_r(array_rand($dwarfs, 2)); 
Array ( 
    [0] => 'second' 
    [1] => 'fifth' 
)

 

shuffle()

Although similar, the shuffle() function diverges from the previous function in its result.

shuffle() randomizes the elements present within an array, which are passed by references, not by value, and at the same time returns a boolean value (true or false) depending on whether the shuffle resulted in success or not.

This function uses the Marsenne Twister algorithm which makes it unsafe and is certainly not suitable for cryptographic purposes.

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
print_r(shuffle($dwarfs)); 
Array ( 
    [0] => Happy 
    [1] => Doc 
    [2] => Sleepy 
    [3] => Grumpy 
    [4] => Bashful 
    [5] => Sneezy 
    [6] => Dopey 
)

 

array_replace()

array_replace() replaces the elements within an array.

It takes two different types of parameters, let's call them an input parameter and a substitute parameter,

The input parameter is an array type parameter and is the array we want to work on, the replacement parameter consists of one or more arrays, and these are the arrays that contain the elements we want to use to replace the elements of the first.

If in the second array we have the same key as in the first the value of the second array will replace the value of the first.

if there is a third array and its keys are also present in the second and the first array, the value of the third array will replace both previous values.

Have a look at the examples below.

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
$originals = array(0 => "Mickey Mouse", 4 => "Pete"); 
$originals2 = array(0 => "Goofy"); 
$disney= array_replace($dwarfs, $originals, $originals2); 
print_r($disney); 
Array ( 
    [0] => Goofy 
    [1] => Grumpy 
    [2] => Happy 
    [3] => Sleepy 
    [4] => Pete 
    [5] => Bashful 
    [6] => Sneezy 
)

array_replace() is not recursive, which means that this function will not recurse into arrays and apply the same process to the inner value. If you need this functionality you can use array_replace_recursive() and specify a key for each array

Here is a short video that explains array_replace in its core

 

array_pad()

When you read the manual you will see that this array function is a bit difficult to understand right away, it took me several minutes to find a use in the real world, but I'm sure that with a little imagination you will find it to be very helpful.

array_pad() adds elements of a specified type (may be integers, strings, etc) to an array.

It takes into consideration three parameters, the first being the input array, 

the second parameter consists of the final size we want the array to become (this is tricky so be careful, if the number is positive we add the values at the end of the array, if the number is negative we add them at the beginning of the input array),

and finally the third parameter is the value to add.

Notice that if you use to pad an associative array using numeric keys as a third parameter, your keys will be renumbered. 

 

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
$padRight = array_pad($dwarfs , 10, 'Snow White'); 
Array ( 
    [0] => Doc 
    [1] => Grumpy 
    [2] => Happy 
    [3] => Sleepy 
    [4] => Dopey 
    [5] => Bashful 
    [6] => Sneezy 
    [7] => Snow White 
    [8] => Snow White 
    [9] => Snow White 
) 
$dwarfs = array('first' => 'Doc', 'second' => 'Grumpy'); 
$padLeft = array_pad($dwarfs , -5, 'Snow White'); 
Array ( 
    [0] => Snow White 
    [1] => Snow White 
    [2] => Snow White 
    [first] => Doc 
    [second] => Grumpy 
)

Read about array_pad() from the official manual

range()

Another way to create arrays automatically is to use the array_range() function, it is very easy and requires three parameters.

The first is the initial value, it can be an integer or a letter,

the second parameter is the final value, it can also be an integer or a letter and allows the array to stop.

The third parameter instead is not mandatory and consists of the length of the three steps, if not entered PHP evaluates it as an integer with the value of 1 by default.

foreach (range(1, 7) as $number) { echo $number; } 
// array(1, 2, 3, 4, 5, 6, 7) 

foreach (range('a', 'g') as $letter) { echo $letter; } 
// array('a', 'b', 'c', 'd', 'e', 'f', 'g');

 

array_fill()

Here is another function whose job is to add values to an array,

array_fill() works much easier than previously seen functions.

It also has three parameters,

the first consists of the initial value of the key and must be an integer and can be either positive or negative,

the second indicates the total number of elements we want in the array, it must also be an integer,

finally, we have the value we want to insert, it can be of mixed type.

$dwarfs = array_fill(17, 3, 'Doc');
Array ( 
    [17] => Doc 
    [18] => Doc 
    [19] => Doc 
) 

$dwarfs = array_fill(-2, 3, 'Doc'); 
Array ( 
    [-2] => Doc 
    [0] => Doc 
    [1] => Doc 
)

 

array_fill_key()

You can see from the example just above that using array_fill() with negative values the result is not the desired one, one way to overcome this obstacle is to define the keys manually.

We can do this thanks to the function: array_fill_key().

First published in PHP 5.2, it takes into account only two parameters, an array containing the keys to be used and a second mixed-type parameter consisting of the values to be inserted.

Obviously like the older brother array_fill() it also returns an array.

$dwarfs = array_fill_keys(range(-2,1),'Doc');
Array ( 
    [-2] => Doc
    [-1] => Doc
    [0] => Doc
    [1] => Doc
)

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
$result = array_fill_keys($keys, 'Snow White');
Array ( 
    [Doc] => Snow White
    [Grumpy] => Snow White
    [Happy] => Snow White
    [Sleepy] => Snow White
    [Dopey] => Snow White
    [Bashful] => Snow White
    [Sneezy] => Snow White
)

array_combine

One of the coolest array functions among those coming in the PHP5 version is undoubtedly array_combine(),

which is also part of the 'creation' functions.

It takes 2 parameters both of array type and returns an associative array that has the elements of the first parameter as keys and the elements of the second array as values.

Obviously, you have to be careful that the elements that will be used as keys are valid (integer or string),

Also, if there are duplicates in the keys the last one will overwrite the others.

$keys = array('dwarfs', 'original', 'dwarfs', 'dwarfs', 'original', 'dwarfs', 'original');
$values = array('Doc', 'Mickey Mouse', 'Grumpy', 'Happy', 'Pete', 'Sleepy', 'Pluto');
array_combine($keys, $values);
Array ( 
    [dwarfs] => Doc
    [original] => Mickey Mouse
    [dwarfs] => Grumpy
    [dwarfs] => Happy
    [original] => Pete
    [dwarfs] => Sleepy
    [original] => Pluto
)

array_walk()

Usually, functions that have callbacks as a parameter may seem scary, array_walk () is a bit less so.

It loops through all the elements of an array and drives a function on them that modifies them.

It takes 3 parameters of which the first two are mandatory, the source array and the callback function, and the third, which can be of different types, which can be used in the callback.

If at the end of the loop there were no errors, array_walk() returns the true boolean otherwise it returns false.

The element's value can be changed in the callback function by specifying the value's parameter as a reference using &$value.

function setString($value,$key,$sentence)
{
    echo "$value $sentence $key";
}
$dwarfs = array(
    'first' => 'Grumpy', 
    'second' => 'Happy', 
    'third' => 'Sleepy', 
    'fourth' => 'Dopey', 
    'fifth' => 'Bashful', 
    'sixth' => 'Sneezy',
    'seventh' => 'Doc'
);

array_walk($dwarfs,"setString"," is the ");
/*
Grumpy is the first
Happy is the second
Sleepy is the third
Dopey is the fourth
Bashful is the fifth
Sneezy is the sixth
Doc is the seventh
*/

array_walk() has a younger brother that is called array_walk_recursive(),

It has arrived in version 5 of PHP.

They share the same format and they have almost the same functionality but by using the recursive you can work with deeper array (also called matrix or arrays inside arrays)

list()

I'm cheating a little here because list() is not an array function but an actual PHP construct,

The reason I entered the list() function in this post is that when I first met it, it confused me, it has a feature that can be used very rarely and at the same time, a different format from any other element in the language.

(maybe it was just my impression, let me know in the comments).

However,

as the manual says, list() assigns variables as if they were an array,

but what does it mean?

In simple words,

it takes an array as a parameter, breaks down all its elements starting from the left (right for PHP5 and minors) and, based on their position, puts them into variables that we define at that moment, you can also skip an element by leaving a blank space.

$disney = array('Doc', 'Grumpy', 'Mickey Mouse', 'Pete');

list($first, $second, $third, $fourth) = $disney;
echo "$first and $second are friends whereas $third and $fourth are enemies";
// Doc and Grumpy are friends whereas Mickey Mouse and Pete are enemies
list($first, $second,, $fourth) = $disney;
echo "$first and $second are friends whereas $fourth has no enemies";
// Doc and Grumpy are friends whereas Pete has no enemies

Here is a deeply explained example of the list function by Sebastian De Deyne

Conclusion

As I said in the previous episode, the array functions are a huge piece to digest.

The good news is that knowing them all is not a necessary requirement.

Not even at the highest levels.

Although it is important for you to know that they exist, you can always use this and the other parts of this guide as a reference and come back here as often as you like.

If you liked this content and the next set of examples on arrays functions, stay tuned and subscribe to the newsletter so you will be notified.

If you want to learn more about PHP array functions take a look at the tutorials already published which are part of this series by clicking on the links below.

PHP array Exposed (part one)
Creation and Manipulation of Arrays


3944-517995.png

Learn to code, gain a new skill, get a new job
Whatever your goal — Treehouse will get you there

They are currently making a free 4-month offer (valued at $ 100).

Have a look at it!
(Affiliate links)


subscribe-Medium.jpg

Top comments (4)

Collapse
 
glennmen profile image
Glenn Carremans

Very interesting! I would love to see more PHP posts, learned a couple new things ❤️

Small tip, if you have a series of posts you can link them together here on DEV.

Collapse
 
anastasionico profile image
anastasionico

Hi Glenn, Thank a lot for your feedback, I appreciate it and I am glad I could help you.
Yes, this is a part of a series that I am writing, I will surely link all the post together, thanks for the hint.
Meanwhile, if you want to see more stuff about PHP feel free to browse over my blog anastasionico.uk/blog

Collapse
 
rockykev profile image
Rocky Kev

This is great! There's a few tricks I didn't know about. Really appreciate it!

Collapse
 
anastasionico profile image
anastasionico

Hi Rocky, Thanks,
Yes i know,
Array functions are a huge field to cover,
I have been coding for years and there were lots of stuff that I learned just while writing this series.
I think it does not depend of experience, what do you think?