useful array functions in PHP

In this tutorial, we will learn about PHP array functions and how to use them. Those array functions are in-built into PHP. There are many array functions in PHP but in this tutorial, we will see most common and regular-use functions with practical examples. Before starting, let’s know more about the array.

What is an Array?

An array is a data structure that stores a fixed-size collection of the same data type elements. The array is a simple data structure where each data element can be accessed directly using its index number.

There are three types of arrays:

  1. Indexed Array
  2. Multi-dimensional Array
  3. Associative Array

Each type of array can be used in a particular set of data or based on requirements. Like, if you just want to store some numbers then you can use an indexed array but if you need to store specific numbers by key name then you need to use an associative array for that.

While working on actual development you need to perform some operations on an array then you can use the array function which helps you to build faster and more effective ways. For example, you need to check particular value is in an array or not. Then we can use either the in_array() function or loop through an array and check a value in every iteration.

Let’s see array functions one by one with practical examples.

array() function

The array() function is used to create a new array in PHP. With this function, we can create any type of array like an indexed array, multi-dimensional array, or associative array.

<?php
	//Indexed Array
	$pets = array('Cat', 'Dog', 'Horse');

	//Associative Array
	$pets = array(
		'Cat' => 'Lucy',
		'Dog' => 'Doller',
		'Horse' => 'Rembo'
	);

	//Multi dimensional Array
	$pets = array(
		array('Cat'),
		array('Dog'),
		array('Horse'),
	);
?>

In the above example, we have defined three arrays as per their type. In the index array, we pass elements only. While using an associative array we have created an array of pets where the key is a type of pet and the value is the name. In a Multidimensional array, we have passed the array as an element.

is_array() Function

In the previous function, we defined an array. But sometimes we need to check particular value is in an array or not and perform operations based on the result.

<?php
	$users = array('alex', 'raj', 'william','josh','john');

	if(in_array('alex', $users)){
		echo "User Found";
	}else{
		echo "User Not Found";
	}
?>

While using this function, It requires three parameters first: a search term, second an array, and last parameter is an option for case sensitivity. By default case sensitive is false. Let’s take an example of case sensitivity.

<?php
	$users = array('alex', 'raj', 'william','josh','john');

	if(in_array('Alex', $users, TRUE)){
		echo "User Found";
	}else{
		echo "User Not Found";
	}
?>

The second example will return not found because this time it will search an array for the user as case-sensitive.

array_keys() Function

The array_keys() function returns a new array containing the keys of an array. It will take an array as a required parameter. While value and strictness are optional parameters. If you pass a value parameter then only keys with specified values are returned. Same as if you pass strict as a parameter, it will return keys by comparing values and type too. Here integer 10 and string 10 will be ignored.

<?php
	$data = array('Bulldog'=>'Charlie', 'German Shephered'=>'Max','Poodle'=>'Walter', 'Boxer'=>'Milo');

	var_dump(array_keys($data));
?>

array(3) {
	[0]=> string(7) "Bulldog"
	[1]=> string(16) "German Shephered"
	[2]=> string(6) "Poodle"
	[3]=> string(5) "Boxer"
}

Let’s take another example, here we get keys of an array where the value is Charlie.

<?php
	$data = array('Bulldog'=>'Charlie', 'German Shephered'=>'Max','Poodle'=>'Walter', 'Boxer'=>'Milo');

	var_dump(array_keys($data, 'Charlie'));
?>

array_values() Function

The array_values() function will return the values of the array into a new array. Here, we just have to pass an array as a parameter.

<?php
	$data = array('Bulldog'=>'Charlie', 'German Shephered'=>'Max','Poodle'=>'Walter', 'Boxer'=>'Milo');

	var_dump(array_values($data));
?>

array_push() Function

The array_push() function is used to add one or more elements to an array. Let’s assume we have created an array and we need to add more elements after creating an array then we can use this function.

<?php
	$colors = array('Red','Blue','Orange');
	array_push($colors, 'Black'); //Adds Single Value
	array_push($colors, 'Yellow', 'Green'); //Adds Multiple Values

	var_dump($colors);
?>

array_pop() Function

The array_pop() function removes the last element from an array. Here, we just have to pass an array.

<?php
	$colors = array('Red','Blue','Orange');
	array_pop($colors);
	var_dump($colors);
?>

array_rand() Function

Sometimes we need to pick a single element from an array randomly then we can use the array_rand() function. It will return keys based on implementations. We can use those keys to use random values.

<?php
	$colors = array('Red','Blue','Orange');
	$random_key = array_rand($colors);
	var_dump($colors[$random_key]);
?>

It will print random elements every time we run the script. We also get multiple random keys same time by passing parameters.

array_unique() Function

The array_unique() function will fetch unique values from an array. It will automatically ignore the duplicate value.

Array unique function takes on input as an array and returns a new array with unique values. Let’s take an example of it.

<?php
	$colors = array('Red','Blue','Orange', 'Red');
	$unique_colors = array_unique($colors);
	var_dump($unique_colors);
?>

array(3) {
	[0]=> string(3) "Red"
	[1]=> string(4) "Blue"
	[2]=> string(6) "Orange"
}

array_search() Function

The array_search() function is used for searching values in an array. It will search the array and return the index of value if found otherwise it will return FALSE.

<?php
	$colors = array('Red','Blue','Orange', 'Red');
	echo array_search('Orange',$colors);
?>

In the above example, it will return 2. But if we search for the color red then it will return 0. So basically it will return the first element’s index if more than one element has the same value.

compact() Function

The compact() function creates an array of variables and their values. The function will automatically create an array from the function’s parameter. It sets the variable name as the key and the variable value as a key value. Let’s take the example of a user.

<?php
$name = "Ajay Patel";
$email = "ajay@gmail.com";
$userData = compact("name", "email");

var_dump($userData);
?>

array(2) {
	["name"]=> string(10) "Ajay Patel"
	["email"]=> string(14) "ajay@gmail.com"
}

array_diff() Function

This function will compare multiple arrays and return a new array with differences. It will compare the first array with the second and third and return values that are not present in others.

<?php
	$colors1 = array("red","green","blue","yellow");
	$colors2 = array("red","black","purple");

	$result=array_diff($colors1,$colors2);
	print_r($result);
?>

In the output of the above example, it will return green, blue, and yellow.

sort() Function

There are many different types of array sorting functions in PHP. Here, we see an example of the sort() function which will sort the array into ascending order.

<?php
	$colors = array("red","green","blue","yellow");
	sort($colors);
	var_dump($colors);
?>

array(4) {
	[0]=> string(4) "blue"
	[1]=> string(5) "green"
	[2]=> string(3) "red"
	[3]=> string(6) "yellow"
}

array_map() Function

The array_map() function sends each value of an array to a custom function and returns an array with new values generated by a custom or user-defined function.

<?php
function result($value)
{
	return $value > 70 ? 'Pass' : 'Fail';
}

$marks = array(70,68,72,85,98);
var_dump(array_map("result",$marks));
?>

In the above example, It will loop through an array and check whether every value is greater than 70 or not. If a value is greater than 70 then it will return pass otherwise fail. Please check the output of the above example:

array(5) {
	[0]=> string(4) "Fail"
	[1]=> string(4) "Fail"
	[2]=> string(4) "Pass"
	[3]=> string(4) "Pass"
	[4]=> string(4) "Pass"
}

array_combine() Function

<?php
	$users = array('alex','rockey','john');
	$marks = array(70,68,72);

	var_dump(array_combine($users,$marks));
?>

array_merge() Function

The array_merge() function merges one or more arrays into a single array.

<?php
	$colors1 = array('Red','Green','Yellow');
	$colors2 = array('Blue', 'Black');

	var_dump(array_merge($colors1,$colors2));
?>

In the above example, it will generate and print a new array that has all colors from both arrays.

Conclusion

Here, we have checked the most popular and useful array functions in PHP. There are many other functions which have individuals use the same as those but you need these functions regularly.