paint-brush
PHP array functions (Exposed)by@anastasionico
1,532 reads
1,532 reads

PHP array functions (Exposed)

by anastasionicoMarch 8th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Let’s be clear!

Company Mentioned

Mention Thumbnail
featured image - PHP array functions (Exposed)
anastasionico HackerNoon profile picture

Let’s be clear!

If you want to become a PHP developer you need to learn arrays functions.

If you are a PHP developer you need to know arrays functions.

Even though is not required to know all of them, having the basic and knowing that they exist will save you a gigantic amount of time during your career.

In this article you will go through the most popular array functions in PHP, read carefully all of them, take note at the one you can refactor your code straight away with and try to understand all the others, I guarantee you that one day you are going to need them.

Introduction: What are arrays?

In PHP and in programming in general, an array is a set of data elements that are stored under a unique name.

Read my article about composite variables in PHP to learn more

An array can contain any type of data, every one of the elements can be allocated and read.

Arrays can contain number, strings and other arrays.

The number of operations you can perform on an array is unlimited.

And for this reason, PHP provides a wide range of built-in features that allow you to read and edit elements within.

Here is the link of the official PHP manual regarding arrays. My recommendation is to have a look at it, even though it might look overwhelming. For this reason, I put together a list of the most important array functions of 2109.

I am sure you will learn a lot from these examples:

array()

It is a PHP construct, incredibly easy to understand. takes a list of values or key-value pairs and creates an array.




$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$disney = array ("dwarfs" => array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'),"originals" => array("Mickey Mouse","Pete", "Goofy", "Minnie Mouse", "Pluto"));

is_array()

It takes a variable as an attribute and returns a boolean value that answers the question: is this attribute an array?

$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');



If (is_array($dwarfs)){echo '$dwarfs is an array';}

In_array()

This PHP function checks if the element you are looking for is present or not in an array




$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');if (in_array("Snow White", $dwarfs)) {echo "Snow White is not a dwarf";}

array_merge()

The array_merge() function merges one or several arrays into a unique array.

In case different elements have the same key, is the last the overrides the others elements

This array function can be used to reset the number of the indices of the array (if the keys are numeric)


$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$originals = array("Mickey Mouse","Pete", "Goofy", "Minnie Mouse", "Pluto");


















array_merge($dwarfs, $originals);Array([0] => Doc[1] => Grumpy[2] => Happy[3] => Sleepy[4] => Dopey[5] => Bashful[6] => Sneezy[7] => Mickey Mouse[8] => Pete[9] => Goofy[10] => Minnie Mouse[11] => Pluto)$dwarfs = array(3 => 'Doc',4 =>'Grumpy',5 => 'Happy');






array_merge($dwarfs);Array ([0] => "Doc"[1] => "Grumpy"[2] => "Happy")

array_keys()

array_keys() returns the keys from an array.

They can be both strings or numerics

The second attribute of this function is called search_value and if it is specified the function return only the keys for that value














$disney = array ("dwarf" => 'Grumpy', "originals" => "Mickey Mouse");array_keys($disney);Array ([0] => dwarfs[1] => originals )$dwarfs = array('Doc', 'Grumpy', 'Doc', 'Sleepy', 'Doc', 'Bashful', 'Sneezy');array_keys($dwarfs, "Doc"); Array([0] => 0[1] => 2[2] => 4)$disney = array("dwarfs" => array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'),"originals" => array("Mickey Mouse","Pete", "Goofy", "Minnie Mouse", "Pluto");





array_keys($disney);Array ([0] => dwarfs[1] => originals)

array_key_exists()

This function check wheater a determinate key or an index exists in an array.

It takes two parameters the first one is the key you want to find the second is the array.

The value returned from this function depends on the result and is of type boolean, if fact it returns true if the value exists or false if it does not.

Very useful in condition statements




$disney = array("dwarf" => 'Grumpy', "originals" => "Mickey Mouse");if (array_key_exists('dwarf', $disney)) {echo "the array disney contains the key dwarf";}

array_values()

The array_values function takes an array as an attribute and returns an array with all values indexing them numerically.

It is useful in case you want to delete keys from an array or transform an array from associative to numeric.






$disney = array ("dwarf" => 'Grumpy', "originals" => "Mickey Mouse");print_r(array_values($disney));Array([0] => Grumpy[1] => Mickey Mouse)

array_count_values()

Let’s pretend you have an array of names,

and you want to find out what is the most common name from this list.

The function array_count_values() takes an array as an attribute and returns an array that has the value of the attribute as a key and the number of instances found as a value.

Let’s see an example;







$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Doc', 'Dopey', 'Doc', 'Grumpy');print_r(array_count_values($dwarfs ));Array([Doc] => 3[Grumpy] => 2[Happy] => 1)

array_shift()

The function array_shift() moves the first value of the array out and returns it as a variable, at the same time it shortens the array taken as an attribute of an element and moving it all down.

All numerical keys in the array will be modified to start counting from zero while the letter keys in an associative array will not be touched.

Notice: the function array_shift() requires a reindexing process on the array, so it must be executed on all elements and indexed.

This means that this practice is quite slow.

To speed up the process you can use array_reverse(), then array_pop(), which does not need to reindex the array and will preserve the keys if you want.











$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$dwarf = array_shift($dwarfs);print_r($dwarfs); Array ([0] => Grumpy[1] => Happy[2] => Sleepy[3] => Dopey[4] => Bashful[5] => Sneezy)// The value of $dwarf is ‘Doc’

array_unshift()

array_unshift() places elements passed as attributes to the front of the selected array.

The list of elements is set up as a whole so that the prefixed elements remain in the same order.

All numeric keys in the array will be modified to start counting from zero while the letter keys will not be changed.

You can insert as many elements as you prefer.











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

array_push()

As the name suggests array_push() pushes the variables passed as an attribute to the end of the array.

It has the same effect as: $array[] =

The length of the matrix increases according to the number of variables inserted.

if you use array_push() to add only one element to the array, it is better to use $array[] = because you do not need to overload the call using a function.

Note that unlike $var[] = where a new array is created, the array_push() function generates a warning if the first argument is not an array.












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

array_pop()

array_pop() removes and returns the value of the last element in the array, shortening the array of an element.

In simple words, the function array_pop() deletes the last element of an array

This function will restore the array input pointer after its use.












$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$dwarf = array_pop(dwarfs);print_r(dwarfs);Array([0] => Doc[1] => Grumpy[2] => Happy[3] => Sleepy[4] => Dopey[5] => Bashful)// The value of $dwarf is 'Sneezy'

array_slice()

The function array_slice() takes four attributes (2 of them are mandatory) and returns a sequence of elements from the indicated array, following the rules specified by the offset and length parameters.

The four parameters are:

The input array. The offset, that can be a positive integer or a negative one and indicates the position the new sequence will start.

Note that the offset indicates the position in the array, not the key.


The Length The length is not mandatory, If it is omitted, the sequence will have everything from the offset to the end of the array.

If the length is given and is positive, then the sequence will have up to that number of elements it contains.

If the length is given and is negative, the sequence will stop many elements from the end of the array.


The preserve_keys attribute The preserve_keys attribute is a boolean, the function array_slice() reorders and restores the indexes of the integer array by default. which means they are going to start from zero.

You can change this behaviour by setting preserve_keys to TRUE. String keys are always preserved, regardless of this parameter.



$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$output = array_slice($dwarfs, 2);// returns 'Happy', 'Sleepy', 'Dopey', 'Bashful' and 'Sneezy'


$output = array_slice($dwarfs, -2, 1);// returns 'Bashful'












$output = array_slice($dwarfs, 0, 3);// returns 'Doc', 'Grumpy', 'Happy'print_r(array_slice($input, 2, -4));Array ([0] => Happy[1] => Sleepy)print_r(array_slice($input, 2, -4, true));Array ([2] => Happy[3] => Sleepy)

array_splice()

The array_splice() function removes elements from an array and, if specified, replaces it with new elements.

It takes four parameters (2 of them are mandatory),

numeric keys in the original array are not preserved.

The parameters are:

The original array

The so-called offset that is a mandatory parameter of type integer, if the number is positive the function removes the portion from the beginning of the array if it is a negative number it starts that number from the end of the array indicated.

The Length is an integer value,

it can be omitted, positive or negative.

If omitted then the function will remove everything from the offset position indicated to the end of the array,

if the number is positive array_splice() will remove that many elements of the array as indicated.

If negative (pay attention here) the function will stop that far from the last element.

You can use count($input) to remove all the elements from the offset to the end of the array.

The replacement array is the parameter that, if specified will replace the removed element, if the replacement is just one element it can be a string and does not have to be an array.

array_splice() returns an array with the removed elements.

Pay attention to the different examples below:



$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');array_splice($dwarfs, 2);// $input is now array('Doc', 'Grumpy')



$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');array_splice($dwarfs, 1, -1);// $input is now array("Doc", "Sneezy")



$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');array_splice($dwarfs, 1, count($dwarfs), "Mickey Mouse");// $input is now array("Doc", "Mickey Mouse")



$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');array_splice($dwarfs, -1, 1, array("Mickey Mouse", "Pete"));// $input is now array("Doc", "Grumpy", "Happy", "Mickey Mouse", "Pete")



$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');array_splice($dwarfs, 3, 0, "Mickey Mouse");// $input is now array("Doc", "Grumpy", "Happy", "Mickey Mouse", "Sleepy", "Dopey", "Bashful", "Sneezy")

array_search()

The function array_search() searches for a value inside an array of elements.

If it finds the element successfully it returns the key of the first element found (only the first) if it does not find any element it returns false or similar.

This function has three parameters:

The first being the element to be searched, it can be of mixed type.

The second parameter is the actual array to search into.

The third parameter is not mandatory and it is a boolean representing the strictness of the search,

by default, it is set to false but if set to true the array_search() will search for identical elements (same value and same type).

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






$key = array_search('Happy', $dwarfs);// return $key = 2;$key = array_search('Grumpy', $dwarfs);// return $key = 1;$key = array_search('Mickey Mouse', $dwarfs);// return false or 0;

array_map()

In my opinion, this function is quite complicated,

array_map() takes a user-made function (usually called callback function) as a first parameter and apply this callback to each one of the elements passed as the second parameter of array_map() itself;

The number of parameters set in the callback needs to be equal to the number of arrays passed as the parameter to the array_map() function.






























function uppercase($dwarf) {return strtoupper($dwarf);}$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$uppercase = array_map("uppercase", $dwarfs);print_r($uppercase);Array ([0] => DOC[1] => GRUMBY[2] => HAPPY[3] => SLEEPY[4] => DOPEY[5] => BASHFUL)// ** Two arrays as parameters **function matchCharacter($character, $brand) {return("The character $character belongs to $brand");}$character = array('Doc', 'Mickey Mouse', 'Happy', 'Sleepy', 'Pete', 'Goofy', 'Sneezy');$brand = array("dwarfs","original", "dwarfs", "dwarfs", "original", "original", "dwarfs")$result = array_map("matchCharacter", $character, $brand);print_r($result); Array ([0] => The character Doc belongs to dwarfs[1] => The character Mickey Mouse belongs to original[2] => The character Happy belongs to dwarfs[3] => The character Sleepy belongs to dwarfs[4] => The character Pete belongs to original[5] => The character Goofy belongs to original[6] => The character Sneezy belongs to dwarfs)

array_unique()

This function removes and returns an array with no duplicate value.

It takes two parameters.

the first parameter is mandatory and it is the array you need to evaluate;

the second parameter is commonly called sort_flag and it is used to modify the sorting behaviour of the array indicated.





The available flags are: SORT_REGULAR that compare items normally (don’t change types); SORT_NUMERIC that compare items numerically; SORT_STRING that compare items as strings; SORT_LOCALE_STRING that compare items as strings, based on the current locale.


This array function will not work on multidimensional arrays. Here is a quick explanation of what multidimensional arrays are.








$dwarfs = array("a" => 'Doc', 'Grumpy', "b" => 'Doc', 'Sleepy', 'Grumpy');$result = array_unique($dwarfs);print_r($result);Array ([a] => Doc[0] => Grumpy[1] => Sleepy)

array_diff()

This function takes at least two or more parameters, all of them need to be of type array, and compares the first array with all the other arrays provided.

Eventually,

it returns the values present in the first array that are not present in any of the other arrays.

Note that elements are considered equal if and only if the first the evaluation === will result in true.








$dwarfsA = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');$dwarfsB = array('Doc', 'Grumpy', 'Happy', 'Dopey', 'Sneezy');$result = array_diff($dwarfsA, $dwarfsB);print_r($result);Array ([3] => Sleepy[5] => Bashful)

If needed you can check deeper dimensions by using array_diff($dwarfsA[0], $dwarfsB[0]).

Conclusion of part 1

Array functions is a topic that extends almost to infinity.

Have you taken notes?

This is a huge bite to be taken in one fell swoop,

for this reason, I divided the article into a series of different blog posts.

An exercise I suggest you do is to go back to the most recent code you wrote and see if you can implement one or more of these array functions.

The advantage, as well as less code to write, is the easiest implementation and that, built-in functions are much faster than implementations that we PHP developers will do by ourselves.

If you liked this content and want to see the next set of example on array functions, stay tuned and subscribe to the newsletter so you will be notified when the next part of the article will be published.

Where to go from here?

As I said this is just the first round of PHP arrays and I will publish other parts soon, meanwhile here you can get more info about PHP depending on your current level:

PHP basics for expert web developers — any newbie here? everything seems overwhelming? no worries this series will bring you from 0 to ready to build your first web application

The complete guide to Object-Oriented Programming — You know the basics of the languages now is time to make things seriously

PHP 7.3 and its new features — stay up-to-date is a must if you want to be relevant in web development

Guide to 24 PHP Frameworks — Do you feel good enough? level up your skills by choosing your first PHP framework.

***

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)

Originally published at anastasionico.uk.

***