PHP Array Functions (with Examples)

PHP provides a vast range of built-in array functions that simplify array manipulation. These functions make easier when working with arrays, from simple operations like counting the number of elements to more advanced tasks such as sorting, merging, or filtering arrays.

Here, we have categorized the full list of 40 array functions in PHP for clarity:

  1. Basic Array Functions
    • array()
    • count()
    • is_array()
  2. Manipulating Array Functions
    • array_push()
    • array_pop()
    • array_shift()
    • array_unshift()
  3. Sorting Array Functions
    • sort()
    • rsort()
    • asort()
    • arsort()
    • ksort()
    • krsort()
    • natsort()
    • natcasesort()
    • usort()
    • uasort()
    • uksort()
  4. Searching in Array Functions
    • in_array()
    • array_search()
  5. Splitting and Combining Array Functions
    • array_slice()
    • array_splice()
    • array_merge()
    • array_merge_recursive()
    • array_combine()
    • array_replace()
    • array_replace_recursive()
  6. Filtering and Mapping
    • array_filter()
    • array_map()
    • array_reduce()
  7. Keys and Values
    • array_keys()
    • array_values()
  8. Miscellaneous Functions
    • array_unique()
    • array_reverse()
    • array_key_exists()
    • array_column()
    • array_diff()
    • array_intersect()
    • array_pad()
    • array_fill()

PHP Basic Array Functions


1. array():

This function was introduced in PHP 3, which is used to create an array in PHP. The general syntax to create an array using array() function is as:

$array_name = array(value1, value2, value3, ...);

Example 1:

<?php
$colors = array("Red", "Green", "Blue");
print_r($colors);
?>
Output:
      Array
     (
       [0] => Red
       [1] => Green
       [2] => Blue
     )

2. count():

The count() function in PHP is used to count the number of elements in an array or something in an object. This function returns an integer representing the number of elements in the array. The general syntax is as:

int count(array $array, int $mode = COUNT_NORMAL)

In this syntax, $array represents the array whose elements are to be counted. This is a required parameter. The second parameter $mode is an optional parameter that determines whether to count all elements in a multidimensional array recursively. It can take two possible values:

  • COUNT_NORMAL: By default, it counts only the top-level elements of an array.
  • COUNT_RECURSIVE: It counts the number of elements recursively in a multidimensional array.


Example 2: Basic Usage

<?php
$fruits = ["Apple", "Banana", "Cherry", "Apple"];
echo count($fruits);
?>
Output: 
      4

Example 3: Using COUNT_RECURSIVE

<?php
$nestedArray = ["Aa", ["Bb", "Cc"], "Dd"];
echo count($nestedArray) . "\n";
echo count($nestedArray, COUNT_RECURSIVE);
?>
Output:
      3
      5

In this example, the count() function without recursion counts only the top-level elements, resulting in 3. With recursion, the count() function also counts elements inside the sub-array, resulting in 5.

3. is_array():

The in_array() function in PHP checks if a specific value exists within an array. This function returns true if the value is found in an array. Otherwise, it returns false. The basic syntax of in_array() function is as:

bool in_array(mixed $value, array $array, bool $strict = false)

In this syntax, the first parameter $value represents the specific value that you want to search for in an array. It can be of any data type, such as integer, string, boolean, or other types.

The second parameter $array specifies the name of an array in which you want to search for an element. It must be valid array. The third parameter is $strict which is an optional. It is set to false by default.

If $strict is true, the function checks for a strict match, meaning that both the value and the type must match exactly. If $strict is false, it allows loose type comparisons.

Example 4: Basic usage

<?php
$fruits = ["Apple", "Banana", "Cherry", "Mango"];

if (in_array("Banana", $fruits)) {
    echo "Banana found.";
} else {
    echo "Banana not found.";
}
?>
Output:
      Banana found.

Example 5: Using Strict Parameter

<?php
$values = [1, 2, "3", 4];
echo in_array(3, $values);
echo in_array(3, $values, true);
?>
Output:
      1

In this example, when PHP executes this statement echo in_array(3, $values);, it gives output 1(i.e. true) because of the loose type comparison. Similarly, when PHP executes the statement echo in_array(3, $values, true);, it gives the output false because of strict comparison. Here, 3 is an integer but “3” is a string.


Example 6: Searching for Boolean Values

<?php
$flags = [true, false, 1, 0];
echo in_array(true, $flags) . "\n"; // Output: 1 (true)
echo in_array(true, $flags, true); // Output: 1 (true)
?>

Example 7: Searching in an Associative Array

<?php
$person = ["name" => "John", "age" => 35];
echo in_array("John", $person); // Output: 1 (true)
echo in_array(25, $person); // Output: (false)
?>

Manipulating Array Functions in PHP


PHP provides many built-in array functions for manipulating arrays. They are:

  • array_push()
  • array_pop()
  • array_shift()
  • array_unshift()

4. array_push():

The array_push() function in PHP adds one or more elements to the end of an array. This function returns the total number of elements in the array after adding the new values. The general syntax is as:

int array_push(array &$array, mixed ...$values)

This function takes two parameters:

1. array &$array

  • array specifies the name of array to which the values will be added.
  • &$array indicates that the array is passed by reference, meaning the original array is directly modified by the function.

2. mixed …$values

  • Here, mixed specifies that you can add any type of values such as integer, string, array, etc..
  • …$values is a variadic parameter, which means you can pass one or more values for adding to the array.

Example 8: Adding a Single Value

<?php
$fruits = ["Apple", "Banana"];
array_push($fruits, "Orange");
print_r($fruits);
?>
Output:
      Array
     (
        [0] => Apple
        [1] => Banana
        [2] => Orange
     )

Example 9: Adding Multiple Values

<?php
$fruits = ["Apple", "Banana"];
$newSize = array_push($fruits, "Amla", "Orange", "Mango");
echo $newSize . "\n";
print_r($fruits);
?>
Output:
       5
       Array
       (
         [0] => Apple
         [1] => Banana
         [2] => Amla
         [3] => Orange
         [4] => Mango
       )

Note that when you use the array_push() function to add values in the array, it always adds them with numeric keys, even if your array has string keys.

The array_push() function appends new values to the array in a sequential order, starting from the highest numeric key. It does not maintain the string keys when adding new elements, but it creates numeric keys for the newly added values.

Example 10:

<?php
$array = [
    "name" => "John",
    "age" => 30
];
array_push($array, "Developer", "USA");
print_r($array);
?>
Output:
      Array
      (
        [name] => John
        [age] => 30
        [0] => Developer
        [1] => USA
      )

5. array_pop():

The array_pop() function in PHP removes the last element of an array and returns it. It directly modifies the original array by removing the last element. If the array is empty, the function returns null. The basic syntax is as:

mixed array_pop(array &$array)

Example 11: Basic usage

<?php
$fruits = ["Apple", "Banana", "Mango", "Guava"];
$lastElement = array_pop($fruits);

echo "Last element removed: " . $lastElement . "\n";
print_r($fruits);
?>
Output:
      Last element removed: Guava
      Array
      (
        [0] => Apple
        [1] => Banana
        [2] => Mango
      )

Example 12: Using Associative Array

<?php
$colors = ["a" => "Red", "b" => "Green", "c" => "Yellow"];
$lastElement = array_pop($colors);

echo "Last element removed: " . $lastElement . PHP_EOL;
print_r($colors);
?>
Output:
      Last element removed: Yellow
      Array
      (
        [a] => Red
        [b] => Green
      )

6. array_shift():

This function removes the first element of an array and returns it. The basic syntax to use array_shift() is as:

mixed array_shift(array &$array)

Example 13:

<?php
$queue = ["A", "B", "C", "D"];
$firstElement = array_shift($queue);
echo "First element removed: " . $firstElement ."\n";
print_r($queue);
?>
Output:
      First element removed: A
      Array
      (
        [0] => B
        [1] => C
        [2] => D
      )

7. array_unshift():

The array_unshift() function in PHP prepends elements to the beginning of an array. The general syntax is as:

int array_unshift(array &$array, mixed ...$values)

Example 14:

<?php
$queue = ["B", "C", "D"];
array_unshift($queue, "A");
print_r($queue);
?>
Output:
      Array
      (
        [0] => A
        [1] => B
        [2] => C
        [3] => D
      )

Sorting Arrays in PHP


PHP provides several built-in functions for sorting arrays. They are: sort(), rsort(), asort(), arsort(), ksort(), krsort(), and array_multisort().

  • The sort() and rsort() functions in PHP sort arrays in ascending and descending order, respectively. However, they do not maintain the association between keys and values. After sorting, the keys are re-indexed starting from 0.
  • The asort() and arsort() functions in PHP sort arrays in ascending and descending order, respectively, but they maintain the association between keys and values.
  • The ksort() and krsort() functions sort associative arrays in ascending and descending order, respectively, based on the keys.
  • The array_multisort() function in PHP is used to sort multiple arrays at once, or a multidimensional array by one or more dimensions.