15+ Most Used PHP Array Functions You Need to Know

After we discuss array in PHP, today we’ll discuss some array functions that we need to know. It will help us a lot to quickly find a solution when we face the same problem.

As we already know, there are a lot of functions related to the array and of course not all of them will be used, therefore, in this short tutorial we’ll only discuss some of them are frequently used (frequently used array functions)

Important note

All the arrays in this article are written using the square brackets [], which only available in PHP 5.4 and above, so if you use PHP version 5.3 and earlier, you need to convert it into array() function.

List of Array Functions We Need to Know

Most Used Array Functions You Need to Know

1 How to count the number of array in PHP

To calculate the number of elements in the array, use count function. This is useful, for example when we want to display the total result of query

$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus']; // From defined array
$vehicle = mysqli_fetch_all($query); // or from database
echo 'Found ' .  count($vehicle) . ' vehicle data';

2 Combining array values into a string

To combine the values of an array, use the join function. This is useful for various purposes, e.g. when building a query to insert data into the database table, for example:

<?php
$vehicle 	= ['Car', 'Motorcycle', 'Bicycle'];
$sql 		= 'INSERT INTO vehicle VALUES ("' . join('","', $vehicle) . '")';
echo $sql;
// Result: INSERT INTO vehicle VALUES ("Car","Motorcycle","Bicycle")

The join function is a function alias of implode function, this means that join exactly do the same task as implode. So when we call the join function PHP will call the implode function in the background.

More about join: PHP: join – Manual

3 Changing all values of the array

To change all the values of the array, use array_map function, this function will call another function that will manipulate the value of the array, this function can be a function provided by PHP (built-in function) or our own function (user defined function)

Example: removing spaces at the beginning and at the end of each value of the array (remove leading and trailing space):

<?php
$vehicle 	= ['Car ', ' Motorcycle', ' Bicycle '];
$trimmed = array_map('trim', $vehicle);
echo '<pre>'; print_r($vehicle); print_r($trimmed);
/* Result:
Array
(
    [0] => Car 
    [1] =>  Motorcycle
    [2] =>  Bicycle 
)
Array
(
    [0] => Car
    [1] => Motorcycle
    [2] => Bicycle
)*/

In the both example above, we use the built-in function: trimtrim($value) ). Another example is changing all values of array to uppercase using user-defined function:

<?php
function toUpper($array_value) {
	return strtoupper($array_value);
}
$vehicle 	= ['Car', 'Motorcycle', 'Bicycle'];
$upper 		= array_map('toUpper', $vehicle);
echo '<pre>'; print_r($upper);
/* Result:
Array
(
    [0] => CAR 
    [1] => MOTORCYCLE
    [2] => BICYCLE 
)*/

More about array_map: PHP: array_map – Manual

4 Check whether an array contains a certain value

To check whether an array has a specific value, use in_array function, e.g.:

<?php
$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
if (in_array('Motorcycle', $vehicle))
{
	echo 'Exists';
}

5 Check whether an array contains a certain key

To check whether an array has a specific key, use array_key_exists function or simply key_exists. Same as join, key_exists is a function alias, which refers to array_key_exists

So, when we call key_exists, PHP will call array_key_exists in the background, for example:

<?php
$car = ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
if (key_exists('type', $car))
{
	echo $car['type']; // Vios
}

Personally, I prefer to use key_exists as of its simplicity

6 Retrieve all keys of an array

To take all keys of an array, use array_keys function, This function will generate a new indexed array with values of the keys, for example:

$car 	= ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
$keys 	= array_keys($car);
echo '<pre>'; print_r($keys);
/* Result:
Array
(
    [0] => merk
    [1] => type
    [2] => year
) */

7 Retrieve all values of an array

Sometimes we need to retrieve all values of an array either to change the associative array to indexed array or retrieve just some part of complex array

To retrieve all value of an array use array_values function. Same as array_keys, this function will generate a new indexed array, for example:

<?php
$car 	= ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
$values = array_values($car);
echo '<pre>'; print_r($values);
/* Result:
Array
(
    [0] => Toyota
    [1] => Vios
    [2] => 2016
)*/

8 Sorting values of an array

To sort the value of the array, we can use asort and arsort function, asort used to sort in ascending order, from the smallest to the largest, for example:

<?php
$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
asort($vehicle);
echo '<pre>'; print_r($vehicle);
/* Result:
Array
(
    [4] => Bicycle
    [0] => Bus
    [1] => Car
    [2] => Motorcycle
    [3] => Truck
)*/

While, if we want to sort in descending order, from the largest to the smallest, we use ksort , to make it easy to memorize, simply make a stand: asort (array sort), arsort (array reverse sort).

Example of arsort:

<?php
$value 		= [90, 70, 85, 65];
asort($value);
echo '<pre>'; print_r($value);

/* Result
Array
(
    [3] => 65
    [1] => 70
    [2] => 85
    [0] => 90
)*/

9 Sorting keys of an array

To sort the keys of an array, we can use two kinds of functions, that are ksort and krsort.

ksort used to sort in ascending order (from the smallest to the largest), while krsort used to sort from the largest to the smallest (descending order), for example:

<?php
$car = ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
krsort($car);
echo '<pre>'; print_r($car);

/* Result
Array
(
    [year] => 2016
    [type] => Vios
    [merk] => Toyota
)*/

Just like the previous, in order to easy to remember, we can make stands: ksort (key sort), while krsort (key reverse sort)

10 Combining arrays in PHP

There are two ways to combine arrays in PHP: using array_merge function or simply use the plus (+) sign, this function is useful  when we want to combine the two arrays results of a database query.

Example of array_merge

<?php
$vehicle 		= ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
$car 			= ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
$merge			= array_merge ($vehicle, $car);
// or $merge 	= $vehicle + $car;
echo '<pre>'; print_r($merge);
/* Result:
Array
(
    [0] => Car
    [1] => Motorcycle
    [2] => Bicycle
    [3] => Truck
    [4] => Bus
    [merk] => Toyota
    [type] => Vios
    [year] => 2016
)*/

More about array_merge: PHP: array_merge – Manual

11 Searching key of value of an array in PHP

We can search for a key of a value in array using array_search function. This can be applied both for indexed array and associative array, for example:

<?php
$vehicle 	= ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
$car 		= ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
$key = array_search('Vios', $car); // type
$key = array_search('Bicycle', $vehicle); // 2

One use of this function is for deleting array element based on its value, for example:

<?php
$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
$key 	 = array_search('Bicycle', $vehicle); // 2
// Deleting Bicycle
unset($vehicle[$key]);

12 Deleting first element of an array in PHP

Sometimes when we want to remove the first element of an array, we feel it become a difficult task as we don’t know its key, fortunately, PHP provides a function named array_shift that take care this task for us.

<?php
$car 	= ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
$key 	= array_shift($car);
echo '<pre>'; print_r($car);
/* Result:
Array
(
    [type] => Vios
    [year] => 2016
) */

13 Adding element to the beginning of an array

Opposite to the previous, to add an element to the beginning of the array, use array_unshift function. NOTE that this function only works with string, for associative array, use array_merge (#10) instead.

Example of array_unshift:

// Indexed Array
$vehicle 		= ['Car', 'Motorcycle', 'Bicycle'];
array_unshift ($vehicle, 'Truck',  'Bus');
echo '<pre>'; print_r($vehicle);
/* Result:
Array
(
    [0] => Truck
    [1] => Bus
    [2] => Car
    [3] => Motorcycle
    [4] => Bicycle
)*/

// Associative array
$car 		= ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
array_unshift ($car, 'Sedan');
echo '<pre>'; print_r($car);
/* Result
Array
(
    [0] => Sedan
    [merk] => Toyota
    [type] => Vios
    [year] => 2016
)

14 Adding element to the end of an array (push)

To add an element to the last position of the array, use the array_push function. Important: This function can not be used to add an associative array, use array_merge (# 10) instead.

Example of array_push:

<?php
$vehicle 	= ['Car', 'Motorcycle', 'Bicycle'];
array_push ($vehicle, 'Truck', 'Bus');
echo '<pre>'; print_r($vehicle);
/* Result:
Array
(
    [0] => Car
    [1] => Motorcycle
    [2] => Bicycle
    [3] => Truck
    [4] => Bus
)*/

$car = ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
array_push ($car, 'Sedan');
echo '<pre>'; print_r($car);
/* Result
Array
(
    [merk] => Toyota
    [type] => Vios
    [year] => 2016
    [0] => Sedan
)
*/

15 Deleting the last element of an array

To remove the last element of the array, use array_pop function, for example:

<?php
$vehicle 	= ['Car', 'Motorcycle', 'Bicycle'];
$pop 		= array_pop ($vehicle);
echo $pop; // Bicycle
echo '<pre>'; print_r($vehicle);
/* Result:
Array
(
    [0] => Car
    [1] => Motorcycle
)

In the example above, the $pop variable contains the last value of the array, that is Bicycles, while the $vehicle variable now only contains Cars and Motorcycle. This can also be applied to an associative array.

16 Reversing the order of array velues

To reverse the order of array values, use array_reverse. One use of this function is when we want to show the title of the article from the latest one.

Example of array_reverse:

<?php
$title 		= ['Title 1', 'Title 2', 'Title 3'];
$reversed	= array_reverse($title);
echo '<pre>'; print_r($reversed);
/* Result:
Array
(
    [0] => Judul 3
    [1] => Judul 2
    [2] => Judul 1
)
*/

17 Finding minimum and maximum value of array values

To find the maximum value of array values, use the max function, while to find the minimum value, use min function, for example:

<?php
$value 	= [90, 70, 85, 65, 80];
$max 	= max($value);
$min 	= min($value);
echo $max; //90
echo $min; //65

Final Words

There are a lot of functions for manipulating array in PHP, these functions can be memorized by itself in line with the number of code that we write and the increasing of complexity of applications that we make.

However, by knowing some of array functions that we have discussed above, at least, when we face the same problem, we can immediately know the solution.

Related Post

3 Responses

  • I am beginner in PHP.. After reading the tutorial got very good understanding with array functions. Pls keep posted good article. It will help the beginners like me.. Thank you very much

  • to find value in the array from array

    <?php
    
    $find_value = [2,5,10,'Motorcycle'];
    
    foreach ($find_value as $value) {
    
    	$array_data = ['Car', 'Motorcycle', 'Bicycle', 'Motorcycle', 'Truck', 'Bus', 5, 10, 5, 2, 15, 2, 5];
    
    	if (in_array($value, $array_data))
    	{
    		$indexes = array_keys($array_data, $value); 
    		echo ''.$value.'Exists: '.count($indexes).' Times.';
    		echo "";
    		print_r($indexes);	
    		echo "";
    	}
    }
    < ?pre>
    ?>

Leave a comment

Like Us

Social