An overview of every main PHP array function

PHP: An overview of every main PHP array function

array_change_key_case(array $array [, int $case = CASE_LOWER ])

Changes the case of all keys in an array

This will return an array with the case changed (to either upper, or lower) for all of the keys.

By default it will make set them to lower case.

It won't affect the values.

<?php
function (){
        $a = ['a'=>'a', 'BBB'=>"bbb", 'cCcC'=>'CcCc'];
        return [
                'lower' => array_change_key_case($a),
                'upper' => array_change_key_case($a,CASE_UPPER),
            ];
    });
?>
Array
(
    [lower] => Array
        (
            [a] => a
            [bbb] => bbb
            [cccc] => CcCc
        )

    [upper] => Array
        (
            [A] => a
            [BBB] => bbb
            [CCCC] => CcCc
        )

)

It also doesn't work on any sub arrays.

<?php
function (){
        $a = [
                'multi_dimensional'=>
                    [
                            'a'=>"a","B"=>"B"
                    ]
        ];
        return  array_change_key_case($a,CASE_UPPER);
    });
?>
Array
(
    [MULTI_DIMENSIONAL] => Array
        (
            [a] => a
            [B] => B
        )

)

array_chunk(array $array , int $size [, bool $preserve_keys = FALSE ])

Split an array into chunks

This is a commonly used function! You should know it very well!

Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

This is useful if you need to do things such as put items into a grid system.

If you use bootstrap then you should recognise the following HTML. Using array_chunk() is an easy way to group your main array into smaller chunks.

<?php
function (){

        $pics = ['jpg1.jpg','jpg2.jpg','jpg3.jpg','jpg4','jpg5'];

        $html = '';

        foreach(array_chunk($pics,2) as $pics_row){
            $html .="
\n"; foreach($pics_row as $pic) { $html .= "\t
$pic
\n"; } $html .= "
\n\n"; } return $html; }); ?>
<div class='row'>
	<div class='col-md-6'> jpg1.jpg </div>
	<div class='col-md-6'> jpg2.jpg </div>
</div>

<div class='row'>
	<div class='col-md-6'> jpg3.jpg </div>
	<div class='col-md-6'> jpg4 </div>
</div>

<div class='row'>
	<div class='col-md-6'> jpg5 </div>
</div>

Here is the raw output:

<?php
function (){
    $pics = ['jpg1.jpg','jpg2.jpg','jpg3.jpg','jpg4.jpg','jpg5.jpg'];

    return array_chunk($pics,2);
});
?>
Array
(
    [0] => Array
        (
            [0] => jpg1.jpg
            [1] => jpg2.jpg
        )

    [1] => Array
        (
            [0] => jpg3.jpg
            [1] => jpg4.jpg
        )

    [2] => Array
        (
            [0] => jpg5.jpg
        )

)

array_column(array $input , mixed $column_key [, mixed $index_key = NULL ])

Return the values from a single column in the input array

Returns an array, with each item of $input with key $column_key.

Sometimes I think it can be easier to work out what is going on if you hard code the 'slow' way to do it. Then it becomes obvious when you should be using these functions. You can think of array_column() as being like:

$return = [];
    $input = [
    ["type"=>"car","colour"=>"red"],
    ["type"=>"bike","colour"=>"blue"],
     ];
     $column_key = "type";

foreach($input as $row) {
    $return[] = $row[$column_key];
}
return $return;

The above would return the same as array_column($input, 'type').

<?php
function (){
        $input = [
                ["id"=>123,"type"=>"car","colour"=>"red"],
                ["id"=>456,"type"=>"bike","colour"=>"blue"],
                ["id"=>789,"type"=>"lorry","colour"=>"pink"],
                ["id"=>234,"type"=>"car","colour"=>"orange"],
        ];
        return array_column($input,'type');
    });
?>
Array
(
    [0] => car
    [1] => bike
    [2] => lorry
    [3] => car
)

If you use the third param you can decide how to key the new array:

<?php
function (){
        $input = [
                ["id"=>123,"type"=>"car","colour"=>"red"],
                ["id"=>456,"type"=>"bike","colour"=>"blue"],
                ["id"=>789,"type"=>"lorry","colour"=>"pink"],
                ["id"=>234,"type"=>"car","colour"=>"orange"],
        ];
        return array_column($input,'type','id');
    });
?>
Array
(
    [123] => car
    [456] => bike
    [789] => lorry
    [234] => car
)

Note: you can also use this on objects (i.e. if $input is an object). It will work with the public properties of the object.

array_combine(array $keys , array $values)

Creates an array by using one array for keys and another for its values

This will return a new array. The keys for the new array will be $keys, and the values will be $values. Quite a simple function.

<?php
function (){
       $keys = ['football', 'tennis', 'house'];
       $values = ['sport','sport','building'];
       return array_combine($keys, $values);
    });
?>
Array
(
    [football] => sport
    [tennis] => sport
    [house] => building
)

array_count_values(array $array)

Counts all the values of an array

This counts how many times each value appears.

<?php
function (){

        $fav_sports = [
            'running',
            'football',
            'tennis',
            'football',
            'snooker',
            'football',
            'swimming',
            'tennis',
            ];

        return array_count_values($fav_sports);
    });
?>
Array
(
    [running] => 1
    [football] => 3
    [tennis] => 2
    [snooker] => 1
    [swimming] => 1
)

array_diff_assoc( array $array1 , array $array2 [, array $... ] )

Computes the difference of arrays with additional index check

This is a commonly used function! You should know it very well!

This will compare two (or more) arrays, and returns the difference.

Unlike array_diff this also looks at the keys.

In the following example you see the "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
function (){
        $array1 = ["a" => "green", "b" => "brown", "c" => "blue", "red"];
        $array2 = ["a" => "green", "yellow", "red"];
        return array_diff_assoc($array1, $array2);
    });
?>
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

array_diff_key(array $array1 , array $array2 [, array $... ])

Computes the difference of arrays using keys for comparison

This function will compare the keys in the arrays, and return any items where their keys are different.

This is the same as array_diff() but looks at the keys (array_diff looks at the values).

<?php
function (){
        $array1 = ['blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4];
        $array2 = ['green' => 5, 'yellow' => 7, 'cyan' => 8];
        return array_diff_key($array1, $array2);
    });
?>
Array
(
    [blue] => 1
    [red] => 2
    [purple] => 4
)

array_diff_uassoc(array $array1 , array $array2 [, array $... ], callable $key_compare_func)

Computes the difference of arrays with additional index check which is performed by a user supplied callback function

This will compare arrays, and return the difference.

It checks the keys, which is similar to array_diff_assoc()), however unlike array_diff_assoc() it uses a callable function to actually check if two keys are the same.

i.e. you define your own function (the last param) and decide yourself if two keys are the same.

<?php
function (){

    // the user definable function to check if the two keys are equal
    $compare_closure = function ($a, $b)
    {
        if ($a === $b) {
            return 0;
        }
        return ($a > $b)? 1:-1;
    };

    $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
    $array2 = array("a" => "green", "yellow", "red");
    return array_diff_uassoc($array1, $array2, $compare_closure);

}
?>
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

array_diff_ukey(array $array1 , array $array2 [, array $... ], callable $key_compare_func )

Computes the difference of arrays using a callback function on the keys for comparison

This function will compare the keys from $array1 and $array2, and return the difference.

This is similar to array_diff_key() - but it uses the user supplied $key_compare_func to do the comparison. (array_diff_key uses its own internal function to do the comparison).

<?php
function (){


    $callable_func = function($key1, $key2)
    {
        if ($key1 == $key2)
            return 0;
        else if ($key1 > $key2)
            return 1;
        else
            return -1;
    };

    $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
    $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

    return array_diff_ukey($array1, $array2, $callable_func);
}
?>
Array
(
    [red] => 2
    [purple] => 4
)

array_diff(array $array1 , array $array2 [, array $... ])

Computes the difference of arrays

This is a commonly used function! You should know it very well!

This is the basic version of the previous 'array_diff_x' functions.

This will return an array of the values that are in $array1 but not in the other array(s).

<?php
function (){
    $array1 = array("a" => "green", "red", "blue", "red");
    $array2 = array("b" => "green", "yellow", "red");
    return array_diff($array1, $array2);
}
?>
Array
(
    [1] => blue
)

array_fill_keys(array $keys , mixed $value)

Fill an array with values, specifying keys

This will return an array with $keys as the keys, and $value for the value for each item in the array.

<?php
function (){
    $keys = array('foo', 5, 10, 'bar');
    return array_fill_keys($keys, 'banana');
}
?>
Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

array_fill(int $start_index , int $num , mixed $value )

Fill an array with values

This is a commonly used function! You should know it very well!

This will return an array that has $num elements. The first key will be $start_index (and each increments 1 for each element). Each value will be $value.

<?php
function (){
    return array_fill(5, 6, 'banana');
}
?>
Array
(
    [5] => banana
    [6] => banana
    [7] => banana
    [8] => banana
    [9] => banana
    [10] => banana
)

Note that if $start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero. I have no idea why it works like this.

array_filter(array $array [, callable $callback [, int $flag = 0 ]])

Filters elements of an array using a callback function

This is a commonly used function! You should know it very well!
If $callable is set:

This will go over every value in the array, and call $callable. If the return value from that closure/function is true then that value from the array is returned into the result array. If it is false, it won't be returned.

$callable can be a closure, function (user defined, or standard php function) that takes two arguments and returns an int.

If $callable is not set:

If $callable is empty (i.e. not a callable function), then array_filter() will return all elements (with keys preserved) where the value is not equal to false.

You can use this function (with no $callable) to remove empty items in an array.

<?php
function (){
    return array_filter([0 => 'foo',
            1 => false,
            2 => -1,
            3 => null,
            4 => '']);
    }
?>
Array
(
    [0] => foo
    [2] => -1
)
<?php
function (){

$array = array(6, 7, 8, 9, 10, 11, 12);

// returns whether the input integer is even:
return array_filter($array,function($var)
{
    return(!($var & 1));
});
            }
?>
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

array_flip(array $array)

Exchanges all keys with their associated values in an array

This is a commonly used function! You should know it very well!

A simple function that puts all of the keys and puts them as the values. And all of the values as keys. I.e. they are flipped!

<?php
function (){
    $input = ['apples'=>"tasty","bananas"=>"nice","pears"=>"yuck"];
    return array_flip($input);
}
?>
Array
(
    [tasty] => apples
    [nice] => bananas
    [yuck] => pears
)

array_intersect_assoc(array $array1 , array $array2 [, array $... ] )

Computes the intersection of arrays with additional index check

Returns an array, with all the values from $array1 that are present in the other arrays. It checks both the keys and values to see if they are present.

<?php
function (){
    $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
    $array2 = array("a" => "green", "b" => "yellow", "blue", "red");
    return array_intersect_assoc($array1, $array2);
}
?>
Array
(
    [a] => green
)

array_intersect_key(array $array1 , array $array2 [, array $... ])

Computes the intersection of arrays using keys for comparison

Returns an array with all items from $array1 that which have keys that are in all of the other arrays.

<?php
function (){
    $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
    $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

    return array_intersect_key($array1, $array2);
}
?>
Array
(
    [blue] => 1
    [green] => 3
)

array_intersect_uassoc(array $array1 , array $array2 [, array $... ], callable $key_compare_func)

Computes the intersection of arrays with additional index check, compares indexes by a callback function

array_intersect_uassoc() will return an array with all of the values from $array1, that are present in the other array(s). It uses the user definable callable $key_compare_func to check if the values are in the other arrays.

$key_compare_func can be a closure, function (user defined, or standard php function) that takes two arguments and returns an int.

<?php
function (){
    $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
    $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

    return array_intersect_uassoc($array1, $array2, "strcasecmp");

            });?>
?>
Array
(
    [b] => brown
)

array_intersect_ukey(array $array1 , array $array2 [, array $... ], callable $key_compare_func)

Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_ukey() will return an array with all of the values from array1, which have matching keys in the other arrays. It uses the $key_compare_func to do the check if a key matches or not.

<?php
function (){
    $key_compare_func =  function ($key1, $key2)
    {
        $return= $key1 == $key2 ? 0 : ($key1 > $key2 ? 1 : -1);
        return $return;
    };

    $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
    $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

    return array_intersect_ukey($array1, $array2, $key_compare_func);

} );?>
?>
Array
(
    [blue] => 1
    [green] => 3
)

(only the keys are checked)

array_intersect(array $array1 , array $array2 [, array $... ])

Computes the intersection of arrays

This is a commonly used function! You should know it very well!

This will return an array with all values from $array1 that are present in all the others.

<?php
function (){
    $array1 = array("a" => "green", "red", "blue");
    $array2 = array("b" => "green", "yellow", "red");
    return array_intersect($array1, $array2);
}
?>
Array
(
    [a] => green
    [0] => red
)

array_key_exists(mixed $key , array $array)

Checks if the given key or index exists in the array

This is a commonly used function! You should know it very well!

A very commonly used array function.

Returns true if $array has a $key key.

(Doesn't look in nested keys in multidimensional arrays.)

<?php
function (){
    $search_array = array('first' => 1, 'second' => 4);
    if( array_key_exists('first', $search_array)) {
        return 'first was in $search_array';
        }
    else {
        return "key was not found";
        }
}
?>
first was in $search_array

This is similar to isset($search_array['first']); - however using isset() will return false if $search_array['first'] = null. Using array_key_exists will return true even if the value is null. This is quite an important point.

Aliases: key_exists()

array_key_first(array $array)

Gets the first key of an array

Introduced in PHP 7.3.0

<?php
function (){
    $array = ['a' => 1, 'b' => 2, 'c' => 3];
    $firstKey = array_key_first($array);
    return $firstKey;
}
?>
a

array_key_last()

Gets the last key of an array

Introduced in PHP 7.3.0

<?php
function (){
                $array = ['a' => 1, 'b' => 2, 'c' => 3];
                $firstKey = array_key_last($array);
                return $firstKey;
            }
?>
c

If you aren't on PHP 7.3, you can fake it with this:

array_keys($input)[count($input)-1];

array_keys(array $array [, mixed $search_value [, bool $strict = FALSE ]])

Return all the keys or a subset of the keys of an array

If you pass this function just $array, it will return an array with just the keys from that input array.

If you pass $search_value to the function, then only keys containing these values are returned. If $strict is false then strict comparisons will be done (===).

<?php
function (){
    $array = array(0 => 100, "color" => "red");
    return array_keys($array);
}
?>
Array
(
    [0] => 0
    [1] => color
)
<?php
function (){
    $array = array("blue", "red", "green", "blue", "blue");
    return array_keys($array,'blue');
}
?>
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)

array_map(callable $callback , array $array1 [, array $... ])

Applies the callback to the elements of the given arrays

This is a commonly used function! You should know it very well!

This will call $callback on each element in the array, and return an array with all the returned values from that callback.

It is a simple function that seems a bit confusing at the start.

You can think of it like this:

$return =[];
$callable = function($input) { return strtoupper($input);};
foreach($items as $item){
    $return[] = $callable($item);
}
return $return;

<?php
function (){
                return array_map('strtoupper', ['hello','WoRlD']);
            }
?>
Array
(
    [0] => HELLO
    [1] => WORLD
)
<?php
function (){
    $cube_function = function ($n)
    {
        return($n * $n * $n);
    };

    return array_map($cube_function, [1, 2, 3, 4, 5]);
}
?>
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

array_merge_recursive(array $array1 [, array $... ])

Merge one or more arrays recursively

This is a commonly used function! You should know it very well!

This will merge the arrays and return the single merged array.

New elements will be added to the end of the array.

It will do it recursively (unlike array_merge).

If two arrays have the same keys and they are a string value, the values will get merged together (i.e. they will overwrite). If the same keys are integers they will not overwrite, but appended to the end.

<?php
function (){
    $ar1 = array("color" => array("favorite" => "red"), 5);
    $ar2 = array(10, "color" => array("favorite" => "green", "blue"));
    return array_merge_recursive($ar1, $ar2);
}
?>
Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

BTW, take note of this - using the + operator for the two arrays:

<?php
function (){
                $ar1 = array("color" => array("favorite" => "red"), 5);
                $ar2 = array(10, "color" => array("favorite" => "green", "blue"));
                return $ar1 + $ar2;
            }
?>
Array
(
    [color] => Array
        (
            [favorite] => red
        )

    [0] => 5
)

array_merge(array $array1 [, array $... ])

Merge one or more arrays

This is a commonly used function! You should know it very well!

This will merge two arrays.

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If two arrays have the same keys and they are a string value, the values will get merged together (i.e. they will overwrite). If the same keys are integers they will not overwrite, but appended to the end.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

<?php
function (){
                $ar1 = array("color" => array("favorite" => "red"), 5);
                $ar2 = array(10, "color" => array("favorite" => "green", "blue"));
                return array_merge($ar1, $ar2);
            }
?>
Array
(
    [color] => Array
        (
            [favorite] => green
            [0] => blue
        )

    [0] => 5
    [1] => 10
)

array_multisort(array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )

Sort multiple or multi-dimensional arrays

This is a commonly used function! You should know it very well!

You can use array_multisort to sort either several arrays at once, or a multidimensional array by one or more dimensions.

I think the best way to understand this is by looking at the examples. Check the PHP docs for definitions of the various array1_sort_flags

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

<?php
function (){
    $ar1 = array(10, 100, 100, 0);
    $ar2 = array(1, 3, 2, 4);

    array_multisort($ar1, $ar2);

    return ['ar1'=>$ar1, 'ar2'=>$ar2];
}
?>
Array
(
    [ar1] => Array
        (
            [0] => 0
            [1] => 10
            [2] => 100
            [3] => 100
        )

    [ar2] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 2
            [3] => 3
        )

)
<?php
function (){
    $ar = array(
            array("10", 11, 100, 100, "a"),
            array(   1,  2, "2",   3,   1)
    );
    array_multisort($ar[0], SORT_ASC, SORT_STRING,
            $ar[1], SORT_NUMERIC, SORT_DESC);
    return $ar;
}
?>
Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 100
            [2] => 100
            [3] => 11
            [4] => a
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
            [3] => 2
            [4] => 1
        )

)

It might seem a bit weird to sort more than one array at once. But it is very useful, as the next example shows.

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive sort, force the sorting order to be determined by a lowercase copy of the original array.

<?php
function (){
    $array = array('Alpha', 'atomic', 'Beta', 'bank');
    $array_lowercase = array_map('strtolower', $array);

    array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

    return $array;
}
?>
Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

array_pad(array $array , int $size , mixed $value)

Pad array to the specified length with a value

array_pad will return an array of $size (actually - the absolute value of $size). If $array was originally smaller than $size, then it will be filled up with new elements with values of $value.

The reason it is the absolute value of $size: if $size is negative, it will be padded to the abs value of $size, but the new elements will be on the 'left' (top) of the array.

<?php
function (){
    $input = array(12, 10, 9);
    $result_pos = array_pad($input, 5, 'padding');
    $result_neg = array_pad($input, -7, 'asdf');
    return ['pos (put padding on right/bottom)'  => $result_pos,
        'neg (left/top)'=>$result_neg];
}
?>
Array
(
    [pos (put padding on right/bottom)] => Array
        (
            [0] => 12
            [1] => 10
            [2] => 9
            [3] => padding
            [4] => padding
        )

    [neg (left/top)] => Array
        (
            [0] => asdf
            [1] => asdf
            [2] => asdf
            [3] => asdf
            [4] => 12
            [5] => 10
            [6] => 9
        )

)

array_pop(array &$array)

Pop the element off the end of array

This is a commonly used function! You should know it very well!

This will take the final element, remove it from an array, and return that element.

<?php
function (){

    $stack = array("orange", "banana", "apple", "raspberry");
    $fruit = array_pop($stack);
    return ['stack' => $stack, 'fruit'=>$fruit];
}
?>
Array
(
    [stack] => Array
        (
            [0] => orange
            [1] => banana
            [2] => apple
        )

    [fruit] => raspberry
)

Associated functions:

array_product(array $array)

Calculate the product of values in an array

Calculates the product all of the values in an array (i.e. multiplies them all together), and returns it.

<?php
function (){
    $a = array(2, 4, 6, 8);
    return array_product($a);
}
?>
384

array_push(array &$array [, mixed $... ])

Push one or more elements onto the end of array

This is a commonly used function! You should know it very well!

array_push() will push item(s) on the end of the array.

This is the exact same as $array[] = $new_item.

<?php
function (){

    $stack = array("orange", "banana");
    array_push($stack, "apple", "raspberry");

    return $stack;
}
?>
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

array_rand(array $array [, int $num = 1 ] )

Pick one or more random keys out of an array

This is a commonly used function! You should know it very well!

If $num is 1 (which it is by default), it will return a random key from $array.

If $num is greater than 1, it will return an array of random keys.

<?php
function (){
    $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
    return array_rand($input, 2);
}
?>
Array
(
    [0] => 0
    [1] => 1
)

array_reduce(array $array , callable $callback [, mixed $initial = NULL ])

Iteratively reduce the array to a single value using a callback function

This is a commonly used function! You should know it very well!

Go through all items in $array, run function $callback, and return just one value ($carry).

It is a bit late so I'm not really wide awake enough to explain this better. But it is a simple concept:

<?php
function (){
    $sum = function ($carry, $item)
    {
        $carry += $item;
        return $carry;
    };

    $product =  function($carry, $item)
    {
        $carry *= $item;
        return $carry;
    };

    $a = array(1, 2, 3, 4, 5);

    return [
    array_reduce($a, $sum),
    array_reduce($a, $product, 10)
            ];
}
?>
Array
(
    [0] => 15
    [1] => 1200
)

array_replace_recursive(array $array1 [, array $... ])

Replaces elements from passed arrays into the first array recursively

This will replace values from $array1 with the same values from $array2 (and subsequent arrays).

  • If a key from the first array exists in the second array, its value will be replaced by the value from the second array.
  • If the key exists in the second array, and not the first, it will be created in the first array.
  • If a key only exists in the first array, it will be left as is.
  • If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.

array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value.

<?php
function (){
    $base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
    $replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
    return array_replace_recursive($base, $replacements);
}
?>
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)

array_replace(array $array1 [, array $... ])

Replaces elements from passed arrays into the first array

This is similar to array_replace_recursive(), but without the recursive-ness!

<?php
function (){
    $base = array("orange", "banana", "apple", "raspberry");
    $replacements = array(0 => "pineapple", 4 => "cherry");
    $replacements2 = array(0 => "grape");
    return array_replace($base, $replacements, $replacements2);
}
?>
Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

array_reverse(array $array [, bool $preserve_keys = FALSE ])

Return an array with elements in reverse order

This is a commonly used function! You should know it very well!

This might surprise you, but this will reverse the array!

if $preserve_keys is true then numeric keys will be preserved. Even if it is false, non-numeric keys are always preserved.

<?php
function (){
    $input  = array("first", 2, array("third"));
    return array_reverse($input);
}
?>
Array
(
    [0] => Array
        (
            [0] => third
        )

    [1] => 2
    [2] => first
)

Searches the array for a given value and returns the first corresponding key if

This is a commonly used function! You should know it very well!
successful

This function will return the key of an element with the same value as $needle. Returns false if it cannot be found.

Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Use the strict === operator to check the return value of this function.
<?php
function (){
    $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
    return array_search('green', $array);
}
?>
2

array_shift(array &$array )

Shift an element off the beginning of array

This is a commonly used function! You should know it very well!

Take the element off the start of $array, and return that shifted value.

<?php
function (){
    $stack = array("orange", "banana", "apple", "raspberry");
    $fruit = array_shift($stack);
    return [$stack,$fruit];
}
?>
Array
(
    [0] => Array
        (
            [0] => banana
            [1] => apple
            [2] => raspberry
        )

    [1] => orange
)

Associated functions:

array_slice(array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]])

Extract a slice of the array

This is a commonly used function! You should know it very well!

array_slice is a commonly used function in PHP.

It will return a 'slice' of an array, from an item at index $offset, and pull out $length elements.

There are quite a few ways to use this function (with negative offset/lengths).

<?php
function (){
    $input = array("a", "b", "c", "d", "e");

    return [array_slice($input, 2),
    array_slice($input, -2, 1),
    array_slice($input, 0, 3)];
}
?>
Array
(
    [0] => Array
        (
            [0] => c
            [1] => d
            [2] => e
        )

    [1] => Array
        (
            [0] => d
        )

    [2] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

)
The $offset Parameter
  • If offset is non-negative, the sequence will start at that offset in the array.
  • If offset is negative, the sequence will start that far from the end of the array.
  • Note that the offset denotes the position in the array, not the key.
The $length Parameter
  • If length is given and is positive, then the sequence will have up to that many elements in it.
  • If the array is shorter than the length, then only the available array elements will be present.
  • If length is given and is negative then the sequence will stop that many elements from the end of the array.
  • If it is omitted, then the sequence will have everything from offset up until the end of the array.
The $preserve_keys Param
  • Note that array_slice() will reorder and reset the integer array indices by default.
  • You can change this behaviour by setting preserve_keys to TRUE.
  • String keys are always preserved, regardless of this parameter.

array_splice(array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]])

Remove a portion of the array and replace it with something else

This is a commonly used function! You should know it very well!

This will remove elements from an array (from $offset, up to a max of $length elements), and put items from $replacement in their place.

If $length is omitted, removes everything from offset to the end of the array.

<?php
function (){
    $input = array("red", "green", "blue", "yellow");
    array_splice($input, 2);
    return $input;
}
?>
Array
(
    [0] => red
    [1] => green
)
<?php
function (){
    $input = array("red", "green", "blue", "yellow");
    array_splice($input, 3, 0, "purple");
    return $input;
}
?>
Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => purple
    [4] => yellow
)
<?php
function (){
    $input = array("red", "green", "blue", "yellow");
    array_splice($input, -1, 1, array("black", "maroon"));
    return $input;
}
?>
Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => black
    [4] => maroon
)

array_sum(array $array)

Calculate the sum of values in an array

This is a commonly used function! You should know it very well!

Add up all the values in the array and return it (as an int or float).

<?php
function (){
    return array_sum([2, 4, 6, 8]);
}
?>
20

array_udiff_assoc(array $array1 , array $array2 [, array $... ], callable $value_compare_func)

Computes the difference of arrays with additional index check, compares data by a callback function

This is similar to array_diff_assoc(), except it does the comparison with the user provided callable function.

It returns an array with all the values from $array1 that are not present in the other array(s). The comparison compares the keys.

<?php
function (){


    $array1 = ['apples' => "red", "bananas" =>"yellow", "oranges"=>"orange"];
    $array2 = ["apples" => "green" ,"bananas"=>"yellow", "grapes"=>"green"];

    return array_udiff_assoc($array1,$array2,function($a,$b) {

        if ($a==$b) {
            return 0;
            }
        return ($a>$b)? 1:-1;

        });

}
?>
Array
(
    [apples] => red
    [oranges] => orange
)

array_udiff_uassoc(array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func)

Computes the difference of arrays with additional index check, compares data and indexes by a callback function

This will return an array with all values from array1 that are not present in the other array(s). It checks both the values (via the provided $value_compare_func) and the keys (via $key_compare_func).

<?php
function (){


    $array1 = ['apples' => "red", "bananas" =>"yellow", "oranges"=>"orange", "foo" =>"bar",];
    $array2 = ["apples" => "green" ,"bananas"=>"green", "grapes"=>"green", "foo" => "notbar",];

    return array_udiff_uassoc($array1,$array2,function($val_a,$val_b) {

        if ($val_a==$val_b) {
            return 0;
        }
        return ($val_a>$val_b)? 1:-1;

    },function($key_a,$key_b) {

        if ($key_a==$key_b) {
            return 0;
        }
        return ($key_a>$key_b)? 1:-1;

        });

}
?>
Array
(
    [apples] => red
    [bananas] => yellow
    [oranges] => orange
    [foo] => bar
)

array_udiff(array $array1 , array $array2 [, array $... ], callable $value_compare_func)

Computes the difference of arrays by using a callback function for data comparison

Similar to array_diff(), but with array_udiff you provide your own comparison function.

<?php
function (){
// Arrays to compare
                $array1 = array(new stdclass, new stdclass,
                        new stdclass, new stdclass,
                );

                $array2 = array(
                        new stdclass, new stdclass,
                );

// Set some properties for each object
                $array1[0]->width = 11; $array1[0]->height = 3;
                $array1[1]->width = 7;  $array1[1]->height = 1;
                $array1[2]->width = 2;  $array1[2]->height = 9;
                $array1[3]->width = 5;  $array1[3]->height = 7;

                $array2[0]->width = 7;  $array2[0]->height = 5;
                $array2[1]->width = 9;  $array2[1]->height = 2;

                $compare_by_area = function ($a, $b) {
                    $areaA = $a->width * $a->height;
                    $areaB = $b->width * $b->height;

                    if ($areaA < $areaB) {
                        return -1;
                    } elseif ($areaA > $areaB) {
                        return 1;
                    } else {
                        return 0;
                    }
                };

                return array_udiff($array1, $array2, $compare_by_area);
            }
?>
Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

array_uintersect_assoc(array $array1 , array $array2 [, array $... ], callable $value_compare_func)

Computes the intersection of arrays with additional index check, compares data by a callback function

This will return an array of all of the values in $array1 that are present in the other arrays. The check function ($value_compare_func) will check the array keys, to see if they're the same.

<?php
function (){


        $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
        $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

        // strcasecmp() will return < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
        // this will return only ['a'=>'green'], as it compares the key only.
        return array_uintersect_assoc($array1, $array2, "strcasecmp");

    });
?>
Array
(
    [a] => green
)

array_uintersect_uassoc(array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func)

Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

This will return an array with all values from $array1 that are in the other arrays. It uses the $value_compare_func to compare the values, and $key_compare_func to compare the keys. (Both keys and values must be equal.)

<?php
function (){
        $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
        $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");
        return array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp");
    });
?>
Array
(
    [a] => green
    [b] => brown
)

array_uintersect(array $array1 , array $array2 [, array $... ], callable $value_compare_func)

Computes the intersection of arrays, compares data by a callback function

This will return an array with all of the values from $array1 that are present in the other arrays. It uses $value_compare_func to compare the values.

<?php
function (){
        $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
        $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

        return array_uintersect($array1, $array2, "strcasecmp");
    });
?>
Array
(
    [a] => green
    [b] => brown
    [0] => red
)

array_unique(array $array [, int $sort_flags = SORT_STRING ])

Removes duplicate values from an array

This is a commonly used function! You should know it very well!

Returns an array of all unique values from $array.

You can define how it checks if items are unique by adding the $sort_flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings (default)
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.
<?php
function (){
        $input = [
                "a" => "green",
                "red",
                "b" => "green",
                "blue", "red"
        ];
        $result = array_unique($input);
        return $result;
    });
?>
Array
(
    [a] => green
    [0] => red
    [1] => blue
)
<?php
function (){
        // mixed types
        $input = [
                4,
                "4",
                "3",
                4,
                3,
                "3"];
        $result = array_unique($input);
        return $result;
    });
?>
Array
(
    [0] => 4
    [2] => 3
)

array_unshift(array &$array [, mixed $... ])

Prepend one or more elements to the beginning of an array

This is a commonly used function! You should know it very well!

This will add the $values (the 2nd parameter, and any subsequent ones) to the start of $array.

All numerical array keys will be modified to start counting from zero while literal keys won't be changed.

<?php
function (){
        $queue = array("orange", "banana");
        array_unshift($queue, "apple", "raspberry");
        return $queue;
    });
?>
Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

array_values(array $array )

Return all the values of an array

This is a commonly used function! You should know it very well!

Return all of the values from an array. They will be keyed numerically.

<?php
function (){
        $array = array("size" => "XL", "color" => "gold");
        return array_values($array);

    });
?>
Array
(
    [0] => XL
    [1] => gold
)

array_walk_recursive(array &$array , callable $callback [, mixed $userdata = NULL ] )

Apply a user function recursively to every member of an array

This will apply the $callback function every item in the array (recursively).

Returns true on success (false on failure).

<?php
function (){
        $fruits = [
                'sweet' => ['a'=>"apple","b"=>"banana"],
                'sour' => 'lemon'
        ];

        global $array_walk_recursive_output;
        $echo_info_func=function($item, $key)
        {
            // sorry for the rubbish way of doing this. This is just to
            // make the example simple...
            global $array_walk_recursive_output;

            $array_walk_recursive_output.= "$key holds $item\n";
        };

        array_walk_recursive($fruits, $echo_info_func);
        return $array_walk_recursive_output;
    });
?>
a holds apple
b holds banana
sour holds lemon

array_walk(array &$array , callable $callback [, mixed $userdata = NULL ])

Apply a user supplied function to every member of an array.

This is a commonly used function! You should know it very well!
<?php
function (){
        $fruits = [
                'sweet' => ['a'=>"apple","b"=>"banana"],
                'sour' => 'lemon'
        ];

        global $array_walk_output;
        $echo_info_func=function($item, $key)
        {
            // sorry for the rubbish way of doing this. This is just to
            // make the example simple...
            global $array_walk_output;

            $array_walk_output.= "$key holds: " . print_r($item,true) ."\n";
        };

        array_walk($fruits, $echo_info_func);
        return $array_walk_output;
    });
?>
sweet holds: Array
(
    [a] => apple
    [b] => banana
)

sour holds: lemon

arsort()

Sort an array in reverse order and maintain index association

This is a commonly used function! You should know it very well!

This will sort an array in reverse order, keeping their indexes.

<?php
function (){
        $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
        arsort($fruits);
        //The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.


        return $fruits;
    });
?>
Array
(
    [a] => orange
    [d] => lemon
    [b] => banana
    [c] => apple
)

asort()

Sort an array and maintain index association

This is a commonly used function! You should know it very well!

This is similar to arsort(), but obviously not in reverse!

This will sort an array (by values), but keeps the keys as they were.

<?php
function (){
        $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
        asort($fruits);
        return $fruits;
    });
?>
Array
(
    [c] => apple
    [b] => banana
    [d] => lemon
    [a] => orange
)

compact()

Create array containing variables and their values

This is a commonly used function! You should know it very well!

This will create an array, containing the values of the parameters of the function call.

<?php
function (){
        $city  = "San Francisco";
        $state = "CA";
        $event = "SIGGRAPH";

        $location_vars = array("city", "state");

        $result = compact("event", "nothing_here", $location_vars);

        return $result;

    });
?>
Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

count( mixed $array_or_countable [, int $mode = COUNT_NORMAL ])

Count all elements in an array, or something in an object

This is a commonly used function! You should know it very well!

This will return a (integer) value of the number of items in an array.

$array_or_countable, as its name implies, can be either a standard array or an object that implements the Countable interface.

If you want to count all items in a multidimensional array then set $mode as COUNT_RECURSIVE (or 1).

<?php
function (){
        $array = [111,222,333,"444","555",];
        return count($array);
    });
?>
5

Recursive count example:

<?php
function (){

        $food = array('fruits' => array('orange', 'banana', 'apple'),
                'veggie' => array('carrot', 'collard', 'pea'));

        return ['recursive_count' => count($food, COUNT_RECURSIVE),
        'normal_count' => count($food)];
        
        });
?>
Array
(
    [recursive_count] => 8
    [normal_count] => 2
)

Aliases: sizeof()

current(array $array)

Return the current element in an array

Aliases: pos()

Return the current element in an array. The current one is the one that the array's internal pointer is 'pointing' at.

<?php
function (){

        $return=[];

        $transport = array('foot', 'bike', 'car', 'plane');
        $return['initial'] = current($transport); // $mode = 'foot';

        // switch internal pointer to next element:
         next($transport);

        // and current() will return the 2nd item in array (index 1)
        $return['after_next'] = current($transport); // $mode = 'foot';

        return $return;

    });?>
?>
Array
(
    [initial] => foot
    [after_next] => bike
)

each()

Return the current key and value pair from an array and advance the array cursor

This function is DEPRECATED in PHP 7.2.0. Do not use this.

end(array &$array)

Set the internal pointer of an array to its last element

This is a commonly used function! You should know it very well!

Set the array's internal pointer to the end of the array (the last element in the array).

It will return the value of the last element or FALSE for empty array.

<?php
function (){

        $fruits = array('apple', 'banana', 'cranberry');
        return end($fruits); // cranberry

        });?>
?>
cranberry

If an array is numerically keyed, then it will return the most recent one to be added to the array.

<?php
function (){
        $a = [];
        $a[1] = 1;
        $a[0] = 0;
        return end($a);
    });?>
?>

extract(array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]])

Import variables into the current symbol table from an array

This is a commonly used function! You should know it very well!

This will take all of the keys in $array, and set a new variable (the variable name = the key name), with the associated value.

Do not use this on untrusted data. If you do extract($_GET);, someone could overwrite any of your variables.
<?php
function (){

        $var_array = ["color" => "blue",
                "size"  => "medium",
                "shape" => "sphere"];

        extract($var_array);

        return "\$color = $color, \$size = $size, \$shape= $shape\n";

    });?>
?>
$color = blue, $size = medium, $shape= sphere

There are several flags that you can use (for the $flags param):

EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL
Prefix all variable names with prefix.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table.
EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the flags.

in_array( mixed $needle , array $haystack [, bool $strict = FALSE ])

Checks if a value exists in an array

This is a commonly used function! You should know it very well!

Is $needle a value inside $haystack array?

By default it will use a loose (==) comparison, but you can set $strict to true to force strict comparisons (===).

If $needle is a string, it is a case sensitive check.

<?php
function (){
        $os = array("Mac", "NT", "Irix", "Linux");
        $irix = in_array("Irix", $os) ? "Got Irix" : "No irix";
        $mac = in_array("mac", $os) ? "Got mac" : "No mac";

        return ['has irix?'=>$irix,'has mac?' =>$mac];
    });?>
?>
Array
(
    [has irix?] => Got Irix
    [has mac?] => No mac
)

key(array $array)

Fetch a key from an array

This is a commonly used function! You should know it very well!

Returns the key of the current element in an array (current element = where the internal pointer is pointing to).

<?php
function (){
        $return='';

        $array = array(
                'fruit1' => 'apple',
                'fruit2' => 'orange',
                'fruit3' => 'grape',
                'fruit4' => 'apple',
                'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
        while ($fruit_name = current($array)) {
            if ($fruit_name == 'apple') {
                $return .= key($array)."\n";
            }
            next($array);
        }

        return $return;
    });?>
?>
fruit1
fruit4
fruit5

krsort(array &$array [, int $sort_flags = SORT_REGULAR ])

Sort an array by key in reverse order

This is a commonly used function! You should know it very well!

Sort an array by key, in reverse order.

<?php
function (){
        $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
        krsort($fruits);
        return $fruits;
    });?>
?>
Array
(
    [d] => lemon
    [c] => apple
    [b] => banana
    [a] => orange
)

ksort(array &$array [, int $sort_flags = SORT_REGULAR ])

Sort an array by key

This is a commonly used function! You should know it very well!

Sort an array by key.

<?php
function (){
        $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
        ksort($fruits);
        return $fruits;
    });?>
?>
Array
(
    [a] => orange
    [b] => banana
    [c] => apple
    [d] => lemon
)

list(mixed $var1 [, mixed $... ])

Assign variables as if they were an array

This is a commonly used function! You should know it very well!

See my guide to PHP array destructuring for a similar topic.

You can use list() to assign variables, from an array.

<?php
function (){

        $info = array('coffee', 'brown', 'caffeine');

        // Listing all the variables
        list($drink, $colour, $power) = $info;
        return "\$drink = $drink, \$colour = $colour, \$power = $power ";
        });
?>
$drink = coffee, $colour = brown, $power = caffeine
<?php
function (){

        $info = array('coffee', 'brown', 'caffeine');

        list($drink, , $power) = $info;
        return "$drink has $power.\n";
    });
?>
coffee has caffeine.

natcasesort(array &$array )

Sort an array using a case insensitive "natural order" algorithm

If you've ever tried to sort strings containing numeric numbers you will know what problem this solves. This will sort items by their 'natural order'.

The natcasesort is a case insensitive sort!

<?php
function (){
        $sort = $nat_case_sort = $nat_sort = ['IMG0.png',
                'img12.png',
                'img10.png',
                'img2.png',
                'img1.png',
                'IMG3.png'];
        sort($sort);
        natcasesort($nat_case_sort);
        natsort($nat_sort);
        return [
                'sort'=>$sort,
                'natural sorted (case insensitive)' =>$nat_case_sort,
                'natural sorted (case sensitive)' =>$nat_sort,
        ];

    });
?>
Array
(
    [sort] => Array
        (
            [0] => IMG0.png
            [1] => IMG3.png
            [2] => img1.png
            [3] => img10.png
            [4] => img12.png
            [5] => img2.png
        )

    [natural sorted (case insensitive)] => Array
        (
            [0] => IMG0.png
            [4] => img1.png
            [3] => img2.png
            [5] => IMG3.png
            [2] => img10.png
            [1] => img12.png
        )

    [natural sorted (case sensitive)] => Array
        (
            [0] => IMG0.png
            [5] => IMG3.png
            [4] => img1.png
            [3] => img2.png
            [2] => img10.png
            [1] => img12.png
        )

)

natsort(array &$array )

Sort an array using a "natural order" algorithm

If you've ever tried to sort strings containing numeric numbers you will know what problem this solves. This will sort items by their 'natural order'.

The natsort is a case sensitive sort!

<?php
function (){
        $sort = $nat_case_sort = $nat_sort = ['IMG0.png',
                'img12.png',
                'img10.png',
                'img2.png',
                'img1.png',
                'IMG3.png'];
        sort($sort);
        natcasesort($nat_case_sort);
        natsort($nat_sort);
        return [
                'sort'=>$sort,
                'natural sorted (case insensitive)' =>$nat_case_sort,
                'natural sorted (case sensitive)' =>$nat_sort,
        ];

    });
?>
Array
(
    [sort] => Array
        (
            [0] => IMG0.png
            [1] => IMG3.png
            [2] => img1.png
            [3] => img10.png
            [4] => img12.png
            [5] => img2.png
        )

    [natural sorted (case insensitive)] => Array
        (
            [0] => IMG0.png
            [4] => img1.png
            [3] => img2.png
            [5] => IMG3.png
            [2] => img10.png
            [1] => img12.png
        )

    [natural sorted (case sensitive)] => Array
        (
            [0] => IMG0.png
            [5] => IMG3.png
            [4] => img1.png
            [3] => img2.png
            [2] => img10.png
            [1] => img12.png
        )

)

next(array &$array )

Advance the internal pointer of an array

This will put the internal pointer for an array to the next element (one place forward).

It returns the next element (the one that the pointer was just moved to).

<?php
function (){

        $return=[];

        $transport = ['foot',
                'bike',
                'car',
                'plane'];

        $return['first_current'] = current($transport); // $mode = 'foot';
        $return['first_next'] = next($transport);    // $mode = 'bike';

        return $return;
        });?>
?>
Array
(
    [first_current] => foot
    [first_next] => bike
)

prev(array &$array)

Rewind the internal array pointer

This is the opposite to next() - it will put the internal pointer of an array back one element.

<?php
function (){

        $return=[];

        $transport = ['foot',
                'bike',
                'car',
                'plane'];

        $return['first_current'] = current($transport); // $mode = 'foot';
        $return['first_next'] = next($transport);    // $mode = 'bike';
        $return['first_prev'] = prev($transport);    // $mode = 'foot';

        return $return;
    });?>
?>
Array
(
    [first_current] => foot
    [first_next] => bike
    [first_prev] => foot
)

range( mixed $start , mixed $end [, number $step = 1 ] )

Create an array containing a range of elements

This is a commonly used function! You should know it very well!

range() will return a new array, with values starting at $start and ending at $end.

If $start = 'a' and $end = 'f', then it will return ['a','b','c','d','e','f'];

<?php
function (){

      return [

          'numbers 1 to 5' => range(1,5),
          //
          'numbers 0 to 101, in steps of 20' => range(1,101,20),
          'a-z, every 5 letters' => range('a','z',5),
          'm to a (backwards), every 4 letters' => range('m','a',4),


          ];
    });?>
?>
Array
(
    [numbers 1 to 5] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )

    [numbers 0 to 101, in steps of 20] => Array
        (
            [0] => 1
            [1] => 21
            [2] => 41
            [3] => 61
            [4] => 81
            [5] => 101
        )

    [a-z, every 5 letters] => Array
        (
            [0] => a
            [1] => f
            [2] => k
            [3] => p
            [4] => u
            [5] => z
        )

    [m to a (backwards), every 4 letters] => Array
        (
            [0] => m
            [1] => i
            [2] => e
            [3] => a
        )

)

reset(array &$array)

Set the internal pointer of an array to its first element

This is a commonly used function! You should know it very well!

Reset the internal pointer, to point at the first element in the array.

<?php
function (){

        $return =[];
        $array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
        $return['initial element'] = current($array) ; // "step one"

// skip two steps
        next($array);
        next($array);
        $return['element after 2 next() calls']= current($array); // "step three"

// reset pointer, start again on step one
        reset($array);
        $return['element after reset() was called'] = current($array); // "step one"

        return $return;
        });?>
?>
Array
(
    [initial element] => step one
    [element after 2 next() calls] => step three
    [element after reset() was called] => step one
)

rsort(array &$array [, int $sort_flags = SORT_REGULAR ])

Sort an array in reverse order

This is a commonly used function! You should know it very well!

The opposite to sort().

This will sort an array from highest to lowest (i.e. in reverse order).

<?php
function (){

        $fruits = ["lemon",
                "orange",
                "banana",
                "apple"];
        rsort($fruits);
        // now they are in reverse alphabetical order.


        return $fruits;


        });?>
?>
Array
(
    [0] => orange
    [1] => lemon
    [2] => banana
    [3] => apple
)

BTW: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys

shuffle(array &$array)

Shuffle an array

This is a commonly used function! You should know it very well!

This will shuffle the array (put it into random order).

<?php
function (){
        $numbers = range(1, 5);
        shuffle($numbers);

        // this demo actually executes this code
        //  - there is a chance that it got sorted into the same order...
        //  trust me, this does shuffle it!
        return $numbers;
    });?>
?>
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

sort(array &$array [, int $sort_flags = SORT_REGULAR ])

Sort an array

This is a commonly used function! You should know it very well!

This will sort the values in the array.

You can set $sort_flag to a range of options such as SORT_NUMERIC (to compare items numerically).

<?php
function (){
        $fruits = array("lemon", "orange", "banana", "apple");
        sort($fruits);
        return $fruits;
    });?>
?>
Array
(
    [0] => apple
    [1] => banana
    [2] => lemon
    [3] => orange
)

uasort(array &$array , callable $value_compare_func)

Sort an array with a user-defined comparison function and maintain index association

This will sort an array (by values), keeping the array keys. The compare function is the $value_compare_func.

<?php
function (){
        $cmp= function ($a, $b) {
            if ($a == $b) {
                return 0;
            }
            return ($a < $b) ? -1 : 1;
        };

// Array to be sorted
        $array = ['a' => 4,
                'b' => 8,
                'c' => -1,
                'd' => -9,
                'e' => 2,
                'f' => 5,
                'g' => 3,
                'h' => -4];

// Sort and print the resulting array
        uasort($array, $cmp);
        return $array;
    });?>
?>
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

uksort( array &$array , callable $key_compare_func)

Sort an array by keys using a user-defined comparison function

This has nothing to do with sorting the United Kingdom out.

Sort an array by its keys, using a user defined function.

<?php
function (){
        $array = [
                "John" => 1,
                "the Earth" => 2,
                "an apple" => 3,
                "a banana" => 4];

        $cmp= function($a, $b)
        {
            $a = preg_replace('@^(a|an|the) @', '', $a);
            $b = preg_replace('@^(a|an|the) @', '', $b);
            return strcasecmp($a, $b);
        };


        uksort($array, $cmp);
        return $array;

    });?>
?>
Array
(
    [an apple] => 3
    [a banana] => 4
    [the Earth] => 2
    [John] => 1
)

usort(array &$array , callable $value_compare_func)

Sort an array by values using a user-defined comparison function

This is a commonly used function! You should know it very well!

This will sort an array, using the provided $value_compare_func function.

Your existing keys will be replaced with new ones.

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

<?php
function (){

$input = array(3, 2, 5, 6, 1);

$cmp = function($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
};


usort($input, $cmp);
return  $input; // 'output' now...

});?>
?>
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 6
)

You can use usort to sort multidimensional arrays

<?php
function (){

$cmp=function ($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
};

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, $cmp);

return $fruits;

});
?>
Array
(
    [0] => Array
        (
            [fruit] => apples
        )

    [1] => Array
        (
            [fruit] => grapes
        )

    [2] => Array
        (
            [fruit] => lemons
        )

)
webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about An overview of every main PHP array function

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

Remove trailing slash (redirect to remove trailing slash) in .htaccess

What is an example of an object literal?

How to get the last character of a string in JS?

How to install and use jpegoptim on Linux CentOS

How to find out what version of Laravel you are using?

How to install jpegtran for Linux CentOS

How to return JSON data to the user in Laravel?

What is Agile software development?

How to get table column names from a database table in Eloquent?

How to find the 2nd most common item in an array?