Frequently used PHP Array Functions Explained

Last Updated: 21 Nov, 2023

What is an array in PHP?

In PHP, array is a type of data structure that allows us to hold more than 1 value at a time. It is a  special variable that can store multiple elements of similar data type under a single variable. An array in PHP is in fact an ordered map which is a type that associates values to keys. So, it provides flexibility for various usage; it can be treated as an array, list, has table, dictionary, collection, stack, queue, and more.

In PHP, we can create 3 types of arrays:

  • Indexed Arrays - These arrays have the numeric index
  • Associative Arrays - These arrays have names keys
  • Multidimensional Arrays - These arrays have one or more arrays in it

Below are the list of most frequently used PHP array functions:

array()

This function is used to create a new array.

Syntax: Indexed Array

array(value1, value2, value3, ..., ...)

Syntax: Associative Array

array(key1=>value1, key2=>value2, key3=>value3, ..., ...)

Example:

<?php
$indexed_array = array(10, 20, 30, 40, 50);
print_r($indexed_array);
/*
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
*/
$associative_array = array(
    'name'=>'W3TechPoint',
    'email'=>'w3techpoint@gmail.com'
);
print_r($associative_array);
/*
Array
(
    [name] => W3TechPoint
    [email] => w3techpoint@gmail.com
)
*/
$multidimensional_array = array(
    'name'=>'W3TechPoint',
    'info'=>array(
        'email' => 'w3techpoint@gmail.com',
        'website' => 'https://www.w3techpoint.com'
    )
);
print_r($multidimensional_array);
/*
Array
(
    [name] => W3TechPoint
    [info] => Array
        (
            [email] => w3techpoint@gmail.com
            [website] => https://www.w3techpoint.com
        )
)
*/
?>

count()

This function is used to count all elements in an array or in a Countable object. This returns the number of elements in an array. It accepts 2 parameters.

Parameters:

  • array: Required parameter that specifies an array or Countable object
  • mode: Optional parameter that specifies whether count the array recursively or not. Default is 0. If 1, it will recursively count the array elements. This is very useful when counting all the elements of a multidimensional array.
Syntax: count(array, mode)

Example:

<?php
$indexed_array = array(10, 20, 30, 40, 50);
echo count($indexed_array); // returns 5

$multidimensional_array = array(
    'name'=>'W3TechPoint',
    'info'=>array(
        'email' => 'w3techpoint@gmail.com',
        'website' => 'https://www.w3techpoint.com'
    )
);
echo count($multidimensional_array, 1); // returns 4
?>

compact()

This function is used to create an array using variables and their values. It take variable number of parameters (minimum 1).

Every parameter can be either:

  • a string containing the name of a variable,
  • or can be an array of variable names.

Any strings that will not match variable names will be skipped. The array can contain other arrays of variable names inside it; compact() manage it recursively.

Syntax: compact(var1, var2, var3, ...)

Example:

<?php
$name = 'W3TechPoint';
$indexed_array = array(10, 20, 30, 40, 50);
print_r(compact('name', 'indexed_array'));
/*
Array
(
    [name] => W3TechPoint
    [indexed_array] => Array
        (
            [0] => 10
            [1] => 20
            [2] => 30
            [3] => 40
            [4] => 50
        )
)
*/
?>

current()

This function is used to return the value of the current element in an array.

Points to note:

  • Each PHP array has an internal pointer to its 'current' element, which is initialised to the first element in the array.
  • The current() function returns the value of the array element that's currently being pointed to by the internal pointer.
  • The current() function does not move the pointer after returning the value.
  • If the internal pointer points beyond the end of the elements list or the array is empty, current() returns false.
Syntax: current(array)

Example:

<?php
$indexed_array = array(10, 20, 30, 40, 50);
echo current($indexed_array); // returns 10
echo next($indexed_array); // returns 20
echo current($indexed_array); // returns 20
echo next($indexed_array); // returns 30
echo current($indexed_array); // returns 30
echo prev($indexed_array); // returns 20
echo current($indexed_array); // returns 20
echo reset($indexed_array); // returns 10
echo current($indexed_array); // returns 10
?>

in_array()

This function is used to search a PHP array for a specific value. It returns TRUE if value is present in array, or FALSE otherwise. It accepts 3 parameters.

Parameters:

  • search: Required parameter that specifies the value to search for
  • array: Required parameter that specifies the array to search in
  • strict: Optional parameter that has a default value of FALSE. It set to TRUE, the in_array() function will also check for the type of the search field.
Syntax: in_array(search, array, strict)

Example:

<?php
$indexed_array = array(10, 20, 30, 40, 50);
if (in_array(20, $indexed_array)) {
    echo "20 found in array.";
}
if (in_array(200, $indexed_array)) {
    echo "200 found in array.";
} else {
    echo "200 not found in array.";
}
/*
20 found in array.
200 not found in array.
*/
?>

array_key_exists()

This function is used to check if the given key exists in the array or not. It returns TRUE if the key is set in the array, or FALSE otherwise. It accepts 2 parameters.

Parameters:

  • key: Required parameter that specifies the key to search for
  • array: Required parameter that specifies the array to search in
Syntax: array_key_exists(key, array)

Example:

<?php
$array = array('name' => 'Ram', 'email' => 'ram@gmail.com', 'mobile' => '9988776600');
if (array_key_exists('name', $array)) {
    echo "Key 'name' found in array.";
}
if (array_key_exists('telephone', $array)) {
    echo "Key 'telephone' found in array.";
} else {
    echo "Key 'telephone' not found in array.";
}
/*
Key 'name' found in array.
Key 'telephone' not found in array.
*/
?>

Note: Please make a note of it that if we skip the key when specifying array, an integer key is generated, starting at 0 and increases by 1 for each value.

array_keys()

This function returns all the keys, numeric and string, of an array. It accepts 3 parameters.

Parameters:

  • array: Required parameter that specifies the array from which the keys will be returned
  • search: Optional and if the values are specified, then only the keys containing these values if present will be returned
  • strict: Optional and specifies the strict comparison (===) for the keys specified in the search values
Syntax: array_keys(array, search, strict)

Example:

<?php
$array = array('name' => 'Ram', 'email' => 'ram@gmail.com', 'mobile' => '9988776600');
$array_keys = array_keys($array);
print_r($array_keys);    
/*
Array
(
    [0] => name
    [1] => email
    [2] => mobile
)
*/
$array_keys = array_keys($array, 'Ram');
print_r($array_keys);
/*
Array
(
    [0] => name
)
*/
$array_keys = array_keys($array, 'ram', true);
print_r($array_keys);
/*
Array
(
)
*/
?>

array_values()

This function returns all the values of an array and stores it in another array. The returned array is  numerically indexed. It accepts single parameter.

Parameters:

  • array: Required parameter that specifies the array from which the values will be returned
Syntax: array_values(array)

Example:

<?php
$array = array('name' => 'Ram', 'email' => 'ram@gmail.com', 'mobile' => '9988776600');
$array_values = array_values($array);
print_r($array_values);    
/*
Array
(
    [0] => Ram
    [1] => ram@gmail.com
    [2] => 9988776600
)
*/
?>

array_chunk()

This function is used to split an array into chunks of new array with the help of length parameter. This function returns a multidimensional numerically indexed array, starting with zero, where each dimension contains length elements. It accepts 3 parameters.

Parameters:

  • array: Required parameter that specifies the array to split
  • length: Required parameter that specifies the size of each chunk. If length is less than 1, error will be thrown
  • preserve_key: Optional parameter that specifies that chunk array will be indexed numerically. Default value is false. If set to true, keys will be preserved.
Syntax: array_chunk(array, length, preserve_key)

Example:

<?php
$array = array('name' => 'Ram', 'email' => 'ram@gmail.com', 'mobile' => '9988776600', 'city' => 'Pune', 'state' => 'Maharashtra');
$array_chunks = array_chunk($array, 2);
print_r($array_chunks);
/*
Array
(
    [0] => Array
        (
            [0] => Ram
            [1] => ram@gmail.com
        )
    [1] => Array
        (
            [0] => 9988776600
            [1] => Pune
        )
    [2] => Array
        (
            [0] => Maharashtra
        )
)
*/
?>

array_column()

This function returns the value from a single column in the input array. It returns an array of values representing a single column from the input array. It accepts 3 parameters.

Parameters:

  • array: Required parameter that specifies a multidimensional array or an array of objects from which to pull a column of values. If an array of objects is provided, then public property can be directly pulled.
  • column_key: Required parameter that specifies the column of values to return. This value can be either an integer key of the column, or it can be a string key name for an associative array or property name. It may be also null to return complete array or object.
  • index_key: Optional parameter that specifies the column to use as the index/keys for the returned array.
Syntax: array_column(array, column_key, index_key)

Example:

<?php
$array = array(
    array('id' => 1001, 'name' => 'Ram', 'email' => 'ram@gmail.com', 'mobile' => '9988776600'),
    array('id' => 1002, 'name' => 'Shyam', 'email' => 'shyam@gmail.com', 'mobile' => '9999999900'),
    array('id' => 1003, 'name' => 'Mohan', 'email' => 'mohan@gmail.com', 'mobile' => '9988888800')
);
$array_column = array_column($array, 'name');
print_r($array_column);
/*
Array
(
    [0] => Ram
    [1] => Shyam
    [2] => MOhan
)
*/
$array_column = array_column($array, 'mobile', 'id');
print_r($array_column);
/*
Array
(
    [1001] => 9988776600
    [1002] => 9999999900
    [1003] => 9988888800
)
*/
?>

array_combine()

This function is used to combine two array and create a combined array. It takes two different or same array as inputs and form a combined array by using one array for keys and another array for values. Both input arrays must have equal number of elements, otherwise it will throw an error. It accepts 2 parameters.

Parameters:

  • array_keys: Required parameter that specifies the array of keys
  • array_values: Required parameter that specifies the array of values
Syntax: array_combine(array_keys, array_values)

Example:

<?php
$array_keys = array('name','email','mobile');
$array_values = array('W3TechPoint','w3techpoint@gmail.com','9988776600');
$array_combined = array_combine($array_keys, $array_values);
print_r($array_combined);
/*
Array
(
    [name] => W3TechPoint
    [email] => w3techpoint@gmail.com
    [mobile] => 9988776600
)
*/
?>

array_merge()

This function is used to merge the elements of one or more arrays into single array. If called without any arguments, it returns an empty array. If two or more array elements have the same key, the last array overrides the others. While merging the arrays, the values of one array are appended to the end of the previous one. It accepts variable parameters.

Parameters:

  • arrays: Required parameter that specifies the variable list of arrays to merge
Syntax: array_merge(array1, array2, array3, ...)

Example:

<?php
$array_1 = array('name' => 'W3Techpoint', 'email' => 'w3techpoint@gmail.com', 9988776600);
$array_2 = array(12345, 'Hello', 'city' => 'Pune');
$array_3 = array(1, 2, 'Maharashtra', 'India');
$array_merged = array_merge($array_1, $array_2, $array_3);
print_r($array_merged);
/*
Array
(
    [name] => W3Techpoint
    [email] => w3techpoint@gmail.com
    [0] => 9988776600
    [1] => 12345
    [2] => Hello
    [city] => Pune
    [3] => 1
    [4] => 2
    [5] => Maharashtra
    [6] => India
)
*/
?>

array_map()

This function allows us to modify all the elements of one or more arrays according to some user-defined condition.

  • It returns an array containing the results of applying the callback to the corresponding value of array used as arguments for the callback.
  • The number of parameters that the callback function accepts must match the number of arrays passed to array_map().
  • Excess input arrays are ignored.
  • If insufficient number of parameters are provided, an ArgumentCountError is thrown.

Parameters:

  • callback: Required parameter that specifies the name of the user-defined function. You can pass null value to perform a zip operation on multiple arrays.
  • array: Required parameter that specifies an array to run through the callback function
  • arrays: Optional parameter that specifies the supplementary variable list of array arguments to run through the callback function.
Syntax: array_map(callback, array, arrays)

Example:

<?php
$callback = function($array) {
    $array = strtoupper($array);
    return $array;
};
$array_1 = array('name' => 'W3Techpoint', 'email' => 'w3techpoint@gmail.com', 9988776600);
$array_result = array_map($callback, $array_1);
print_r($array_result);
/*
Array
(
    [name] => W3TECHPOINT
    [email] => W3TECHPOINT@GMAIL.COM
    [0] => 9988776600
)
*/
?>

 

 

Thank You, Please Share.

Recommended Posts

PHP 7 New Features and Enhancements Explained

PHP 7 New Features and Enhancements Explained

In this easy and simplified tutorial, we are going to learn about most awaited PHP version (PHP 7) and its super important features and enhancements.

IMAGE

PHP OOP Interfaces Explained

An Interface allows you to create programs that specifies which methods a class must implement, without defining how those methods are implemented.

Frequently used PHP String Functions Explained

Frequently used PHP String Functions Explained

In this article you will learn about most frequently used PHP string functions with the help of beautifully explained examples.