PHP array functions (Exposed)
Tags: php, phparray, phparrayfunction
Published: 2019-03-08 13:28:14

---
title: PHP array functions (Exposed)
published: true
description: Learn now, the most important array functions provided by PHP
tags: php, php array, php array function
cover_image: https://thepracticaldev.s3.amazonaws.com/i/o0d6nnyz22jeeu60sqf3.jpg
series: PHP arrays exposed
---

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.  
 &nbsp;

 

 
## 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](http://anastasionico.uk/blog/composite-variable-in-php)

 

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](http://php.net/manual/en/book.array.php). My recommendation is to have a look at it, even though it might look overwhelming.&nbsp; 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.

 
```php
$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?

 
```php
$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

 
```php
$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy');
if (in_array("Snow White", $dwarfs)) {
    echo "Snow White is not a dwarf"; 
}
```
 
## &nbsp;
 
## 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)

 
```php
$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

 
```php
$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 
)
```
 
## &nbsp;
 
## 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

 
```php
$disney = array ("dwarf"  => 'Grumpy', "originals" => "Mickey Mouse"); 
if (array_key_exists('dwarf', $disney)) {
    echo "the array disney contains the key dwarf"; 
}
```
 
## &nbsp;
 
## 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.

 
```php
$disney = array ("dwarf"  => 'Grumpy', "originals" => "Mickey Mouse");
print_r(array_values($disney));
Array (     
    [0] => Grumpy     
    [1] => Mickey Mouse 
)
```
 
## &nbsp;
 
## 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;

 
```php
$dwarfs = array('Doc', 'Grumpy', 'Happy', 'Doc', 'Dopey', 'Doc', 'Grumpy');
print_r(array_count_values($dwarfs ));
Array (     
    [Doc] => 3     
    [Grumpy] => 2     
    [Happy] => 1 
)
```
 
## &nbsp;
 
## 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.

 
```php
$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.

 
```php
$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  
)
```
 
## &nbsp;
 
## 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.

 
```php
$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  
)
```
 
## &nbsp;
 
## 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.

 
```php
$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'
```
 
## &nbsp;
 
## 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:  
 &nbsp;

 

**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.&nbsp;

 

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.

 
```php
$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 
)
```
 
## &nbsp;
 
## array\_splice()
 

The _array\_splice()_ function removes elements from an array and, if specified, replaces it with new elements.&nbsp;

 

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.  
 &nbsp;

 

**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.&nbsp;

 

array\_splice() returns an array with the removed elements.

 

Pay attention to the different examples below:

 
```php
$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")
```
 
## &nbsp;
 
## 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).

 
```php
$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;
```
 
## &nbsp;
 
## 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.

 
```php
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 
)
```
 
## &nbsp;
 
## 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](https://www.tutorialspoint.com/php/php_arrays.htm) are.

 
```php
$dwarfs = array("a" => 'Doc', 'Grumpy', "b" => 'Doc', 'Sleepy', 'Grumpy');
$result = array_unique($dwarfs); 
print_r($result); 
Array (     
    [a] => Doc     
    [0] => Grumpy     
    [1] => Sleepy 
)
```
 
## &nbsp;
 
## 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.

 
```php
$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.

 
## &nbsp;
 
## 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](http://anastasionico.uk/blog/php-basics-for-web-developer)** - 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](http://anastasionico.uk/blog/object-oriented-programming)** - You know the basics of the languages now is time to make things seriously

 

**[PHP 7.3 and its new features](http://anastasionico.uk/blog/php-73)** - stay up-to-date is a must if you want to be relevant in web development

 

**[Guide to 24 PHP Frameworks](http://anastasionico.uk/blog/guide-to-php-frameworks-part-1)** - Do you feel good enough? level up your skills by choosing your first &nbsp;PHP framework.  
 &nbsp;

 

\*\*\*

 

[![](http://anastasionico.uk/img/1/3944-517995.png)](http://treehouse.7eer.net/c/1374240/294479/3944)

 
### 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).](http://treehouse.7eer.net/c/1374240/294479/3944)

 

[Have a look at it!.](http://treehouse.7eer.net/c/1374240/294479/3944)

 

([Affiliate links](http://treehouse.7eer.net/c/1374240/294479/3944))

     
[ ![subscribe-Medium.jpg](https://cdn.filestackcontent.com/RrGR27noRgSByWvS0Sck)](http://eepurl.com/dIZqjf)