Signup/Sign In

PHP Array Functions

We have covered basics of array, indexed arrays, associative arrays and multidimensional arrays. Now let's dive deep into arrays and learn about the in-built functions for array processing in PHP.

In general practice, using the right array function will save you a lot of time as they are pre-defined in PHP libraries and all you have to do is call them to use them.


Commonly used PHP5 Array Functions

Below we have a list of some commonly used array functions in PHP:

sizeof($arr)

This function returns the size of the array or the number of data elements stored in the array.

It is just like count($arr) method, that we used in previous tutorials while traversing the array.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");
echo "Size of the array is: ". sizeof($lamborghinis);

?>

Size of the array is: 3


is_array($arr)

To check whether the provided data is in form of an array, we can use the is_array() function. It returns True if the variable is an array and returns False otherwise.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// using ternary operator
echo is_array($lamborghinis) ? 'Array' : 'not an Array';

$mycar = "Urus";

// using ternary operator
echo is_array($mycar) ? 'Array' : 'not an Array';

?>

Array not an Array


in_array($var, $arr)

When using an array, we may often want to check whether a certain value is present in the array or not. For example, if get a list of certain cars, like we do in almost all our examples, to check if a certain car is added into the array, we can use the in_array function.

Let's take an example and see,

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// new concept car by lamborghini
$concept = "estoque";

echo in_array($concept, $lamborghinis) ? 'Added to the Lineup' : 'Not yet!'

?>

Not yet!

As we can see unlike the other functions above, this one takes two arguments, one is the value to be searched in the array, and the second one is the array itself.


print_r($arr)

Although this is not an array function, but it deserves a special mention here, as we can use this function to print the array in the most descriptive way possible. This function prints the complete representation of the array, along with all the keys and values.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");
print_r($lamborghinis);

?>

Array ( [0] => "Urus" [1] => "Huracan" [2] => "Aventador" )


array_merge($arr1, $arr2)

If you want to combine two different arrays into a single array, you can do so using this function. It doesn't matter whether the arrays to be combined are of same type(indexed, associative etc) or different types, using this function we can combine them into one single array.

Let's take an example where we will merge an indexed array and an associative array.

<?php

$hatchbacks = array(
        "Suzuki" => "Baleno",
        "Skoda" => "Fabia",
        "Hyundai" => "i20",
        "Tata" => "Tigor"
    );

// friends who own the above cars
$friends = array("Vinod", "Javed", "Navjot", "Samuel");

// let's merge the two arrays into one
$merged = array_merge($hatchbacks, $friends);

print_r($merged);

?>

Array ( [Suzuki] => Baleno [Skoda] => Fabia [Hyundai] => i20 [Tata] => Tigor [0] => Vinod [1] => Javed [2] => Navjot [3] => Samuel )


array_values($arr)

In an array, data is stored in form of key-value pairs, where key can be numerical(in case of indexed array) or user-defined strings(in case of associative array) and values.

If we want to take all the values from our array, without the keys, and store them in a separate array, then we can use array_values() function.

Let's take the array $merged formed in the example above,

<?php

$hatchbacks = array(
        "Suzuki" => "Baleno",
        "Skoda" => "Fabia",
        "Hyundai" => "i20",
        "Tata" => "Tigor"
    );

// friends who own the above cars
$friends = array("Vinod", "Javed", "Navjot", "Samuel");

// let's merge the two arrays into one
$merged = array_merge($hatchbacks, $friends);

//getting only the values
$merged = array_values($merged);

print_r($merged);

?>

Array ( [0] => Baleno [1] => Fabia [2] => i20 [3] => Tigor [4] => Vinod [5] => Javed [6] => Navjot [7] => Samuel )


array_keys($arr)

Just like values, we can also extract just the keys from an array. Let's use this function to extract the keys from the array $merged.

<?php

//getting only the keys
$keys = array_values($merged);

print_r($keys);

?>

Array ( [0] => Suzuki [1] => Skoda [2] => Hyundai [3] => Tata [4] => 0 [5] => 1 [6] => 2 [7] => 3 )


array_pop($arr)

This function removes the last element of the array. Hence it can be used to remove one element from the end.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// removing the last element
array_pop($lamborghinis);

print_r($lamborghinis);

?>

Array ( [0] => Urus [1] => Huracan )


array_push($arr, $val)

This function is the opposite of the array_pop() function. This can be used to add a new element at the end of the array.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// adding a new element at the end
array_push($lamborghinis, "Estoque");

print_r($lamborghinis);

?>

Array ( [0] => Urus [1] => Huracan [2] => Aventador [3] => Estoque )


array_shift($arr)

This function can be used to remove/shift the first element out of the array. So, it is just like array_pop() function but different in terms of the position of the element removed.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// removing the first element
array_shift($lamborghinis);

print_r($lamborghinis);

?>

Array ( [0] => Huracan [1] => Aventador )

Similar to this, we have another function array_unshift($arr, $val) to add a new value($val) at the start of the array(as the first element).


sort($arr)

This function sorts the array elements in ascending order. In case of a string value array, values are sorted in ascending alphabetical order.

Some other sorting functions are: asort(), arsort(), ksort(), krsort() and rsort().

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador", "Estoque");

// sort the array
sort($lamborghinis);

print_r($lamborghinis);

?>

Array ( [0] => Aventador [1] => Estoque [2] => Huracan [3] => Urus )


array_map('function_name', $arr)

If you want to perform certain operation on all the values stored in an array, you can do it by iterating over the array using a for loop or foreach and performing the required operation on all the values of the array.

Or, you can use the function array_map(). All we have to do is define a separate function to which we will provide the values stored in the array one by one(one at a time) and it will perform the operation on the values. Let's have an example,

<?php

function addOne($val) {
    // adding 1 to input value
    return ($val + 1);
}

$numbers = array(10, 20, 30, 40, 50);

// using array_map to operate on all the values stored in array
$numbers = array_map('addOne', $numbers);

print_r($numbers)

?>

Array ( [0] => 11 [1] => 21 [2] => 31 [3] => 41 [4] => 51 )

The function array_walk($arr, 'function_name') works just like the array_map() function.


array_flip($arr)

This function interchange the keys and the values of a PHP associative array.

<?php

$hatchbacks = array(
        "Suzuki" => "Baleno",
        "Skoda" => "Fabia",
        "Hyundai" => "i20",
        "Tata" => "Tigor"
    );
    
// we can directly print the result of array flipping
print_r(array_flip($hatchbacks));

?>

Array ( [Baleno] => Suzuki [Fabia] => Skoda [i20] => Hyundai [Tigor] => Tata )


array_reverse($arr)

This function is used to reverse the order of elements, making the first element last and last element first, and similarly rearranging other array elements.

<?php

$num = array(10, 20, 30, 40, 50);
// printing the array after reversing it
print_r(array_reverse($num));

?>

Array ( [0] => 50 [1] => 40 [2] => 30 [3] => 20 [4] => 10 )


array_rand($arr)

If you want to pick random data element from an array, you can use the array_rand() function. This function randomly selects one element from the given array and returns it.

In case of indexed array, it will return the index of the element, in case of associative array, it will return the key of the selected random element.

<?php

$colors = array("red", "black", "blue", "green", "white", "yellow");

echo "Color of the day: ". $colors[array_rand($colors)];

?>

Color of the day: green

Every time you run the above script, it will return a random color value from the array.


array_slice($arr, $offset, $length)

This function is used to create a subset of any array. Using this function, we define the starting point($offset, which is the array index from where the subset starts) and the length(or, the number of elements required in the subset, starting from the offset).

Let's take an example,

<?php

$colors = array("red", "black", "blue", "green", "white", "yellow");

print_r(array_slice($colors, 2, 3));

?>

Array ( [0] => blue [1] => green [2] => white )