The PHP Array cheatsheet

The PHP Array cheatsheet.

PHP still has an important place in the ecosystem of web development languages. Used on the back-end, it is very often necessary to manipulate arrays in PHP. The aim of this article is to present as many methods and tips as possible for manipulating arrays in PHP.

The article is organised in such a way as to present firstly the common and simple manipulations, and finally to end on the specificities and less recurrent needs.

The basics of manipulating a PHP array

Create a PHP array

To construct an array in PHP, simply use the array() method designed for this purpose:

$array = array(1, 3, 6, 9);

Create an array in PHP with the array() method and no initial value:

$array = array();

Create a php array associative using the array() method:

$array = array(
	“name” => “Max”,
	“age” => 25
);

Create a PHP array in an interval with a step defined by the range() method:

$array = range(1, 9, 3); // [1, 3, 6, 9]

Create a PHP array of variables with their values using the compact() method:

$var1 = 1;
$var2 = 2;
compact(“var1”, “var2”); // [ [var1] => 1, [var2] => 2

Create a PHP array using custom indices using the array_fill_keys() method:

$arrayIndex = array(1, 2, 3, 4);
$array = array_fill_keys($arrayIndex, 0); // [1 => 0, 2 => 0, 3 => 0, 4 => 0]

Create an array in PHP with the elements of an array as its index and the elements of another array as its value, using the array_combine() method:

$arrayIndex = array(1, 2, 3, 4);
$arrayValue = array(1, 3, 6, 9);
$array = array_combine($arrayIndex, $arrayValue); // [1 => 1, 2 => 3, 3 => 6, 4 => 9]

Adding and deleting elements in an array in PHP.

To add a string, number, array or other type of variable to an array in PHP, the array_push() method is the main method used:

$array = array(1, 3, 6, 9);
array_push($array, 11); // [1, 3, 6, 9, 11]

To add an element to the beginning of a PHP array, there is a variant with the array_unshift() method that works in a similar way:

$array = array(1, 3, 6, 9);
array_unshift($array, 0); // [0, 1, 3, 6, 9]

One important point: you can add several elements in a row by adding arguments to array_push() or array_unshift().

By keeping the variable from the array_unshift() transformation, it is possible to receive the new size of the array.

Add a PHP array as new elements of another PHP array:

$array = array(1, 3, 6, 9);
echo [...$array, …[11, 13, 15, 17]]; // 1, 3, 6, 9, 11, 13, 15, 17

Add the same value several times from a row in an array in PHP using the array_fill() method:

$array = array_fill(2, 3, 11); // [2 => 11, 3 => 11, 4 => 11]

Delete an element from a PHP array using the unset() method:

$array = array(1, 3, 6, 9);
unset($array[1]); // [1, 6, 9]

Note that this method does not allow the array to be re-indexed after the element has been deleted.

Delete an element and re-index the PHP array with array_splice():

$array = array(1, 3, 6, 9);
array_splice($array, 1, 1); // [1, 6, 9]

Deleting the last element of an array in PHP using the array_pop() method:

$array = array(1, 3, 6, 9);
array_pop($array); // [1, 3, 6]

An alternative is to use the array_shift() method to delete the first element of an array in PHP:

$array = array(1, 3, 6, 9);
array_shift($array); // [3, 6, 9]

Delete duplicate elements in a PHP array using the array_unique() method:

$array = array(1, 3, 6, 3, 9);
array_unique($array); // [1, 3, 6, 9]

Retrieving the size of a PHP array.

The main technique for retrieving the size of an array is to use the .count() method:

$array = array(1, 3, 6, 9);
echo count($array); // 4

There is an alternative to count() with the sizeof() method:

$array = array(1, 3, 6, 9);
echo sizeof($array); // 4

Retrieving precise values from a PHP table.

Find the element located at index ‘a’ by enclosing it in square brackets:

$array = array(1, 3, 6, 9);
echo $array[0]; // 1

Present all the elements in a PHP array using a for loop:

$array = array(1, 3, 6, 9);
for( $x=0 ; $x<count($array) ; $x++) {
	echo $array[x];
}

To retrieve part of an array in an interval, the standard practice is to use the array_slice(startIndex, endIndex) method:

$array = array(1, 3, 6, 9);
echo array_slice($array, 0, 2); // 1, 3

An important piece of information to know for array_slice(), the interval excludes the last element corresponding to $end.

Find the index of the first element corresponding to a value in the argument using the array_search() method:

$array = array(1, 3, 6, 9);
echo array_search(3, $array); // 1

An alternative is to find the last element corresponding to a value defined as an argument using an inversion transformation of the array:

$array = array(1, 3, 6, 9);
echo array_search(3, array_reverse($array)); // 3

Get the number of occurrences of each term in an array in PHP using array_count_values():

var array =  [1, 3, 3, 6, 9, 6, 6];
print_r(array_count_values($array)); 
/*
Array(
	[1] => 1
	[3] => 2
	[6] => 3
	[9] => 1
)
*/

Retrieve the set of elements not common to two arrays in PHP using the array_diff() method:

$array =  [1, 3, 6, 9];
$array2 = [9, 11, 13, 15];
array_diff($array, $array2); // [1, 3, 6, 11, 13, 15]

Other arrays can be added as arguments to the array_diff() method.

Retrieve the sum of the elements in a PHP array using the array_sum() method:

$array = array(1, 3, 6, 9);
array_sum($array); // 19

Retrieve the product of the elements in a PHP array using the array_product() method:

$array = array(1, 3, 6, 9);
array_product($array); // 162

Retrieve one or more random elements from a PHP array using array_rand():

$array = array(1, 3, 6, 9);
array_rand($array, 2); // [3, 6]

Retrieve the first index of an array in PHP using the array_key_first() method:

$array = array(1, 3, 6, 9);
array_key_first($array); //0

Alternatively, you can retrieve the last index from an array in PHP using the array_key_last() method:

$array = array(1, 3, 6, 9);
array_key_last($array); // 3

Retrieve all the php keys array associative using the array_keys() method:

$array = array(1, 3, 6, 9);
array_keys($array); // [0, 1, 2, 3]

Retrieving the current value of an array in PHP using the current() method:

$array = array(1, 3, 6, 9);
current($array); // 1

There is an alternative alias for the current() method using the pos() method:

$array = array(1, 3, 6, 9);
pos($array); // 1

Retrieve an associative key from a PHP array using the key() method:

$array = array(“a” => 1);
key($array); // a

Validating the characteristics of a PHP table:

Check that a variable is present in an array in PHP with in_array():

$array = array(1, 3, 6, 9);
echo in_array(3, $array); // true

Check that all the elements of an array in PHP respect the logical condition defined with the array_reduce() method:

$array = array(1, 3, 6, 9);
echo array_reduce($array, ($result, $element) => $result && $element < 10, true); // true

Validates that at least one element in a PHP array validates the logical condition defined using the array_reduce() method:

$array = array(1, 3, 6, 9);
echo array_reduce($array, ($result, $element) => $result || $element < 3, true); // true

Check that an array in PHP is considered to be a list using the array_is_list() method:

$array = array(1, 3, 6, 9);
array_is_list(); // false

An array in PHP is a list if its indices are integers, starting from 0 with a step of 1.

Check that an index exists in a php array associative using the array_key_exist() method:

$array = array(1 => 1, 2=> 3, 3 => 6, 4 => 9);
array_key_exist(3, $array); // true

An alias alternative also exists for checking the existence of an index in an php array associative using the key_exist() method:

$array = array(1 => 1, 2=> 3, 3 => 6, 4 => 9);
key_exist(3, $array); // true

Useful operations for processing data in a PHP table.

Transforming a PHP table.

Merge two PHP arrays into a single array using the array_merge() method:

$array = array(1, 3, 6, 9);
$array2 = array(11, 13, 15, 17)
$arrayMerged = array_merge($array, $array2); // [1, 3, 6, 9, 11, 13, 15, 17] 

Important point: you can merge more than two arrays by adding new arrays as arguments to the array_merge() method.

Convert a PHP array into a string using the implode() method:

$array = array(1, 3, 6, 9);
echo implode(“and”, $array); // 1 and 3 and 6 and 9

Transform a string variable into a PHP array using the explode() method:

$string = “Hello I am here”;
$array = explode(“ “, $string); // [“Hello”, “I”, “am”, “here”]

Inverting elements in an array in PHP using the array_reverse() method:

$array = array(1, 3, 6, 9);
array_reverse($array); // [9, 6, 3, 1]

Transform the value of each element in an array by means of a function definition using the array_walk() method:

$array = array(1, 3, 6, 9);
array_walk($array,  ($element) =>{
	$element ++;
}); // [2, 4, 7, 10]

An alternative using the array_map() method can also be used to apply a transformation to each element of an array in PHP:

$array = array(1, 3, 6, 9);
array_map(($el) => $el + 1 ,$array); // [2, 4, 7, 10]

Keep only part of the array based on a logical condition using the array_filter() method:

$array = array(1, 3, 6, 9);
echo array_filter($array, ($el) => $el > 3); // [6, 9]

Transform all the elements of an interval into a single value using the array_replace() and array_fill() methods:

$array = array(1, 3, 6, 9);
array_replace($array, array_fill(0, 2, 0)); // [0, 0, 0, 9]

Transform a PHP array into several smaller arrays of the same size using array_chunk():

$array = array(1, 3, 6, 9);
array_chunk($array, 2); // [1, 3] [6,9]

Add a specific number of elements to a PHP array with a value defined using the array_pad() method:

$array = array(1, 3, 6, 9);
array_pad($array, 6, 11) // [1, 3, 6, 9, 11, 11]

Invert indices and values in a PHP array using the array_flip() method:

$array = array(1, 3, 6, 9);
array_flip($array); // [1 => 0, 3 => 1, 6 => 2, 9 => 3]

Modify the elements of a PHP array at specific indices using another array and the array_replace() method:

$array = array(1, 3, 6, 9);
$arrayReplace = array( 0 => 11, 9 => 13);
$arrayResult = array_replace($array, $arrayReplace); // [11, 3, 6, 13]

By using the array_replace() method, you can add new arguments as a replacement array.

Sorting the elements of a PHP array.

Sort the elements of an array in PHP in ascending order using the sort() method:

$array = array(3, 1, 9, 6);
sort($array); // [1, 3, 6, 9]

Alternatively, you can sort the elements of an array in PHP in descending order using the rsort() method:

$array = array(3, 1, 9, 6);
rsort($array); // [9, 6, 3, 1]

Shuffle the elements in a PHP array using the shuffle() method:

$array = array(3, 1, 9, 6); 
shuffle($array); // [3, 6, 9, 1]

Retrieve the elements present in two separate PHP arrays using the array_intersect() method:

$array = array(1, 3, 6, 9);
$array2 = array(6, 9, 11, 13);
$arrayResult = array_intersect($array, $array2); // [6, 9]

When using the array_intersect() method with associative arrays, the php keys array are retained in the final result.

Sort the elements of an associative PHP array in descending order using the arsort() method:

$array = array(2 => 1, 1 => 3, 0 => 6, 3 => 9);
$arrayResult = arsort($array); // [9, 6, 3, 1]

The advantage of using arsort() is that the sort by descending order array retains the associative keys of the sorted elements.

An alternative exists for sorting the elements of an associative PHP array in ascending order using the asort() method:

$array = array(2 => 1, 1 => 3, 0 => 6, 3 => 9);
$arrayResult = asort($array); // [1, 3, 6, 9]

As with arsort(), the asort() method is used to retain associative keys while the array is being processed.

Sort the elements of an associative array in PHP in descending order of indices using the krsort() method:

$array = array(2 => 1, 1 => 3, 0 => 6, 3 => 9);
$arrayResult = krsort($array); // [9, 1, 3, 6]

Alternatively, you can sort the associative array in PHP in ascending order of indices, this time using the ksort() method:

$array = array(2 => 1, 1 => 3, 0 => 6, 3 => 9);
$arrayResult = ksort($array); // [6, 3, 1, 9]

Sort the elements of a PHP array with a natural sorting algorithm using the natsort() method:

$array = array(“a1”, “a11”, “a2”, “a13”);
$arrayResult = natsort($array); // [“a1”, “a2”, “a11”, “a13”]

The advantage of natsort() over sort() is that it has a better understanding of string sorting.

Presenting a PHP table.

Read an array in PHP from the console in a readable format using print_r():

$array = array(1, 3,  6, 9);
print_r($array); 
/*
Array(
[0] => 1
[1] => 3
[2] => 6
[3] => 9
)
*/

Give a list of variables the value of the elements of a PHP array using the list() method:

$array = array(1, 3,  6, 9);
list($a, $b, $c, $d) = array();
print(‘The element are: $a, $b, $c and $d); 

Return all the elements present in a PHP array using the array_values() method:

$array = array(1, 3,  6, 9);
print(array_values($array)); 
/*
Array (
	[0] => 1,
	[1] => 3
[2] => 6
[3] => 9
):
*/
Photo Maxime Macé

Maxime Macé

Simple passionné de thématiques diverses et variées. J’apprécie enrichir mes connaissances dans les disciplines techniques comme l’informatique, les sciences et l’ingénierie, mais aussi dans les domaines merveilleux de la philosophie, l’art et la littérature.

Prenons contact

Vous souhaitez me contacter suite à la lecture de cet article ? Merci de renseigner votre adresse électronique et je vous recontacterai dans les plus brefs délais.

CV Ingénieur développeur informatique

CV Étudiant PhD Artificial Intelligence

Portfolio Artist designer