{{announcement.body}}
{{announcement.title}}

PHP Array Functions Exposed

DZone 's Guide to

PHP Array Functions Exposed

In this post, we take a look at the most popular and important array functions in PHP and see just how they work.

· Web Dev Zone ·
Free Resource

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 basics 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 all of them carefully, take note of the ones you can use to refactor your code straight away, and try to understand all the others — I guarantee you that one day you are going to need them.

If, instead, you feel like you need to brush up on some other characteristics of the language and learn some new tricks, have a look at the basics of PHP.

Introduction: What Are Arrays?

In PHP, and in programming in general, an array is a composite variable type, i.e. a set of data elements that are stored under a unique name. An array can contain any type of data and 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 arrays.

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:

About the Series

This blog post that belongs to the series "PHP Arrays Exposed."

If you haven't already read the other articles, have a look at them:

array()

This is a PHP construct, and is incredibly easy to understand. It 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, the last one 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 numbers.

The second attribute of this function is called search_value and if it specifies that 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 checks whether 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: it returns true if the value exists or false if it does not.

This function proves 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 array_shift()function 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 moves 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.

Simply put, the array_pop() function 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 array_slice() function takes thre attributes (two 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 three parameters are:

  • The input array. The offset that can be a positive integer or a negative one and indicates the position of the new sequence. 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. If the length is given and is negative, the sequence will stop that 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 behavior 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 them with new elements.

It takes four parameters (two of them are mandatory)l numeric keys in the original array are not preserved.

(If the examples you've seen so far seem a little too complicated, take a look at the basics of PHP,
This will allow you to come back here and see everything clearer.)

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. This can be omitted, or made positive or negative. If omitted then the function will remove everything from the offset position indicated from 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.

Take a look at the code for 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 array_search() function 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 a callback function) as a first parameter and applies this callback to each one of the elements passed as the second parameter of the array_map() itself.

The number of parameters set in the callback need 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 behavior of the array indicated.

The available flags are:

  • SORT_REGULAR that compares items normally (don’t change types).

  • SORT_NUMERIC that compares items numerically.

  • SORT_STRING that compares items as strings.

  • SORT_LOCALE_STRING that compares items as strings, based on their current location.

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

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, and, for this reason, I divided the article into a series of different blog posts.

The second part of this series focuses on the creation and manipulation of arrays and their elements, while reading the third part, you will learn all the secrets about filtering elements within arrays.

The fourth is all about sorting, getting the elements to appear in the order you want them to appear.

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, beside having less code to write, is the easy implementation and that built-in functions are much faster than implementations 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.

Originally published at anastasionico.uk.

***

This article is part of a series.

Subscribe to the newsletter using the form below and get notified every time new content is published!

Topics:
web dev ,php tutorial for beginners ,php tutorial ,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 }}