PHP Language


Arrays All Versions

1.0
2.0
3.0
4.0
4.1
4.2
4.3
5.0
5.1
4.4
5.2
5.3
5.4
5.5
7.0
5.6

This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 14

    An array can be initialized empty:

    $foo = array();
    // Shorthand notation available since PHP 5.4
    $foo = [];
    

    An array can be initialized with a set of values:

    // Creates a simple array of three strings
    $fruit = array('apples', 'pears', 'oranges');
    // In the shorthand notation available since PHP 5.4
    $fruit = ['apples', 'pears', 'oranges'];
    // This notation also produces the same three string array as above
    $fruit = [];
    $fruit[] = 'apples';
    $fruit[] = 'pears';
    $fruit[] = 'oranges';
    

    An array can also be initialized with custom indexes (also called an associative array):

    // A simple array
    $fruit = array('first' => 'apples', 'second' => 'pears', 'third' => 'oranges');
    // Shorthand notation available since PHP 5.4
    $fruit = ['first' => 'apples', 'second' => 'pears', 'third' => 'oranges'];
    // Key and value can also be set as follows
    $fruit['first'] = 'apples';
    

    If the variable hasn't been used before, PHP will create it automatically:

    $foo[] = 1;     // Array( [0] => 1 )
    $bar[][] = 2;   // Array( [0] => Array( [0] => 2 ) )
    

    While convenient, this might make the code harder to read.

    The index will usually continue where you left off. PHP will try to use numeric strings as integers:

    $foo = [2 => 'apple', 'melon'];  // Array( [2] => 'apple', [3] => 'melon' )
    $foo = ['2' => 'apple', 'melon']; // same as above
    $foo = [2 => 'apple', 'this is index 3 temporarily', '3' => 'melon'] // same as above! The last entry will overwrite the second!
    

    To initialize an array with fixed size you can use SplFixedArray (PHP >= 5.3)

    $array = new SplFixedArray(3);
    $array[0] = 1;
    $array[1] = 2;
    $array[2] = 3;
    $array[3] = 4; // RuntimeException
    

    To initialize an array with a dynamic size but with n non empty elements (e.g. a placeholder) you can use a loop as follows:

    $myArray = array();
    $sizeOfMyArray = 5;
    $fill = 'placeholder';
    
    for ($i = 0; $i < $sizeOfMyArray; $i++) {
      $myArray[] = $fill;
    }
    
    // print_r($myArray); results in the following:
    Array ( [0] => placeholder [1] => placeholder [2] => placeholder [3] => placeholder [4] => placeholder ) 
    

    If all your placeholders are the same then you can also use the function called array_fill:

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

    Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

    Note: If the start_index is negative it will start with the negative index and continue from 0 for the following elements.

    $a = array_fill(5, 6, 'banana'); // Array (5 => 'banana', 6 => 'banana', ..., 10 => 'banana')
    $b = array_fill(-2, 4, 'pear'); // Array (-2 => 'pear', 0 => 'pear', ..., 2 => 'pear')
    

    Conclusion: With array_fill you are more limited for what you can actually do. The loop is more flexible and opens you a wider range of opportunities.

    Whenever you want an array filled with a range of numbers (e.g. 1-4) you could either append every single element to an array or use the range function:

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

    Create an array containing a range of elements. The first two parameters are required. They set the start and end point of the range, the third one is optional and defines what amount it should add to the previous element. Default step size is 1. Lets set a range from 0 to 4. With a stepsize of 1 it would be like this: 0, 1, 2, 3, 4. If we increase the step size to 2 (range(0, 4, 2)) it would be: 0, 2, 4.

    $array = [];
    $array_with_range = range(1, 4);
    
    for ($i = 1; $i <= 4; $i++) {
      $array[] = $i;
    }
        
    print_r($array); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
    print_r($array_with_range); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
    
  • 6

    To apply a function to every item in an array, use array_map(). This will return a new array.

    $array = array(1,2,3,4,5);
    //each array item is iterated over and gets stored in the function parameter.
    $newArray = array_map(function($item) {
        return $item + 1;
    }, $array);
    

    $newArray now is array(2,3,4,5,6);.

    Instead of using an anonymous function, you could use a named function. The above could be written like:

    function addOne($item) {
        return $item + 1;
    }
    
    $array = array(1, 2, 3, 4, 5);
    $newArray = array_map('addOne', $array);
    

    Another way to apply a function to every item in an array is array_walk() and array_walk_recursive(). The callback passed into these functions take both the key/index and value of each array item. These functions will not return a new array, instead a boolean for success. For example, to print every element in a simple array:

    $array = array(1, 2, 3, 4, 5);
    array_walk($array, function($value, $key) {
        echo $value . ' ';
    });
    // prints "1 2 3 4 5"
    

    The value parameter of the callback may be passed by reference, allowing you to change the value directly in the original array:

    $array = array(1, 2, 3, 4, 5);
    array_walk($array, function(&$value, $key) {
        $value++;
    });
    

    $array now is array(2,3,4,5,6);

    For nested arrays, array_walk_recursive() will go deeper into each sub-array:

    $array = array(1, array(2, 3, array(4, 5), 6);
    array_walk_recursive($array, function($value, $key) {
        echo $value . ' ';
    });
    // prints "1 2 3 4 5 6"
    

    Note: array_walk and array_walk_recursive let you change the value of array items, but not the keys. Passing the keys by reference into the callback is valid but has no effect.

  • 4

    Use array_key_exists() or isset() or !empty():

    $map = [
        'foo' => 1,
        'bar' => null,
        'foobar' = '',
    ];
    
    array_key_exists('foo', $map); // true
    isset($map['foo']); // true
    !empty($map['foo']); // true
    
    array_key_exists('bar', $map); // true
    isset($map['bar']); // false
    !empty($map['bar']); // false
    

    Note that isset() treats a null valued element as non-existent. Whereas !empty() does the same for any element that equals false (using a weak comparision; for example, null, '' and 0 are all treated as false by !empty()). While isset($map['foobar']); is true, !empty($map['foobar']) is false. This can lead to mistakes (for example, it is easy to forget that the string '0' is treated as false) so use of !empty() is often frowned upon.

    Note also that isset() and !empty() will work (and return false) if $map is not defined at all. This makes them somewhat error-prone to use:

    // note "long" vs "lang", a tiny typo in the variable name
    $my_array_with_a_long_name = ['foo' => true];
    array_key_exists('foo', $my_array_with_a_lang_name); // shows a warning
    isset($my_array_with_a_lang_name['foo']); // returns false
    

    You can also check for ordinal arrays:

    $ord = ['a', 'b']; // equivalent to [0 => 'a', 1 => 'b']
    
    array_key_exists(0, $ord); // true
    array_key_exists(2, $ord); // false
    

    Noticed that isset() has better performance than array_key_exists() as the latter is a function and the former a language construct.

I am downvoting this example because it is...

Syntax

  • $array = array('Value1', 'Value2', 'Value3'); // Keys default to 0, 1, 2, ...,
  • $array = array('Value1', 'Value2', ); // Optional trailing comma
  • $array = array('key1' => 'Value1', 'key2' => 'Value2', ); // Explicit keys
  • $array = array('key1' => 'Value1', 'Value2', ); // Array ( ['key1'] => Value1 [1] => 'Value2')
  • $array = ['key1' => 'Value1', 'key2' => 'Value2', ]; // PHP 5.4+ shorthand
  • $array[] = 'ValueX'; // Append 'ValueX' to the end of the array
  • $array['keyX'] = 'ValueX'; // Assign 'valueX' to key 'keyX'
  • $array += ['keyX' => 'valueX', 'keyY' => 'valueY']; // Adding/Overwrite elements on an existing array

Parameters

ParameterDetail
KeyThe key is the unique identifier and index of an array. It may be a string or an integer. Therefore, valid keys would be 'foo', '5', 10, 'a2b', ...
ValueForeach key there is a corresponding value (null otherwise). The value takes all kinds of input (e.g. String, Number, Boolean, Array, Object, Closure).

Remarks

Remarks

Still have question about Arrays? Ask Question

Initializing an array

14

An array can be initialized empty:

$foo = array();
// Shorthand notation available since PHP 5.4
$foo = [];

An array can be initialized with a set of values:

// Creates a simple array of three strings
$fruit = array('apples', 'pears', 'oranges');
// In the shorthand notation available since PHP 5.4
$fruit = ['apples', 'pears', 'oranges'];
// This notation also produces the same three string array as above
$fruit = [];
$fruit[] = 'apples';
$fruit[] = 'pears';
$fruit[] = 'oranges';

An array can also be initialized with custom indexes (also called an associative array):

// A simple array
$fruit = array('first' => 'apples', 'second' => 'pears', 'third' => 'oranges');
// Shorthand notation available since PHP 5.4
$fruit = ['first' => 'apples', 'second' => 'pears', 'third' => 'oranges'];
// Key and value can also be set as follows
$fruit['first'] = 'apples';

If the variable hasn't been used before, PHP will create it automatically:

$foo[] = 1;     // Array( [0] => 1 )
$bar[][] = 2;   // Array( [0] => Array( [0] => 2 ) )

While convenient, this might make the code harder to read.

The index will usually continue where you left off. PHP will try to use numeric strings as integers:

$foo = [2 => 'apple', 'melon'];  // Array( [2] => 'apple', [3] => 'melon' )
$foo = ['2' => 'apple', 'melon']; // same as above
$foo = [2 => 'apple', 'this is index 3 temporarily', '3' => 'melon'] // same as above! The last entry will overwrite the second!

To initialize an array with fixed size you can use SplFixedArray (PHP >= 5.3)

$array = new SplFixedArray(3);
$array[0] = 1;
$array[1] = 2;
$array[2] = 3;
$array[3] = 4; // RuntimeException

To initialize an array with a dynamic size but with n non empty elements (e.g. a placeholder) you can use a loop as follows:

$myArray = array();
$sizeOfMyArray = 5;
$fill = 'placeholder';

for ($i = 0; $i < $sizeOfMyArray; $i++) {
  $myArray[] = $fill;
}

// print_r($myArray); results in the following:
Array ( [0] => placeholder [1] => placeholder [2] => placeholder [3] => placeholder [4] => placeholder ) 

If all your placeholders are the same then you can also use the function called array_fill:

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

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Note: If the start_index is negative it will start with the negative index and continue from 0 for the following elements.

$a = array_fill(5, 6, 'banana'); // Array (5 => 'banana', 6 => 'banana', ..., 10 => 'banana')
$b = array_fill(-2, 4, 'pear'); // Array (-2 => 'pear', 0 => 'pear', ..., 2 => 'pear')

Conclusion: With array_fill you are more limited for what you can actually do. The loop is more flexible and opens you a wider range of opportunities.

Whenever you want an array filled with a range of numbers (e.g. 1-4) you could either append every single element to an array or use the range function:

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

Create an array containing a range of elements. The first two parameters are required. They set the start and end point of the range, the third one is optional and defines what amount it should add to the previous element. Default step size is 1. Lets set a range from 0 to 4. With a stepsize of 1 it would be like this: 0, 1, 2, 3, 4. If we increase the step size to 2 (range(0, 4, 2)) it would be: 0, 2, 4.

$array = [];
$array_with_range = range(1, 4);

for ($i = 1; $i <= 4; $i++) {
  $array[] = $i;
}
    
print_r($array); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
print_r($array_with_range); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

Applying a function to each element of an array

6

To apply a function to every item in an array, use array_map(). This will return a new array.

$array = array(1,2,3,4,5);
//each array item is iterated over and gets stored in the function parameter.
$newArray = array_map(function($item) {
    return $item + 1;
}, $array);

$newArray now is array(2,3,4,5,6);.

Instead of using an anonymous function, you could use a named function. The above could be written like:

function addOne($item) {
    return $item + 1;
}

$array = array(1, 2, 3, 4, 5);
$newArray = array_map('addOne', $array);

Another way to apply a function to every item in an array is array_walk() and array_walk_recursive(). The callback passed into these functions take both the key/index and value of each array item. These functions will not return a new array, instead a boolean for success. For example, to print every element in a simple array:

$array = array(1, 2, 3, 4, 5);
array_walk($array, function($value, $key) {
    echo $value . ' ';
});
// prints "1 2 3 4 5"

The value parameter of the callback may be passed by reference, allowing you to change the value directly in the original array:

$array = array(1, 2, 3, 4, 5);
array_walk($array, function(&$value, $key) {
    $value++;
});

$array now is array(2,3,4,5,6);

For nested arrays, array_walk_recursive() will go deeper into each sub-array:

$array = array(1, array(2, 3, array(4, 5), 6);
array_walk_recursive($array, function($value, $key) {
    echo $value . ' ';
});
// prints "1 2 3 4 5 6"

Note: array_walk and array_walk_recursive let you change the value of array items, but not the keys. Passing the keys by reference into the callback is valid but has no effect.

Check if key exists

4

Use array_key_exists() or isset() or !empty():

$map = [
    'foo' => 1,
    'bar' => null,
    'foobar' = '',
];

array_key_exists('foo', $map); // true
isset($map['foo']); // true
!empty($map['foo']); // true

array_key_exists('bar', $map); // true
isset($map['bar']); // false
!empty($map['bar']); // false

Note that isset() treats a null valued element as non-existent. Whereas !empty() does the same for any element that equals false (using a weak comparision; for example, null, '' and 0 are all treated as false by !empty()). While isset($map['foobar']); is true, !empty($map['foobar']) is false. This can lead to mistakes (for example, it is easy to forget that the string '0' is treated as false) so use of !empty() is often frowned upon.

Note also that isset() and !empty() will work (and return false) if $map is not defined at all. This makes them somewhat error-prone to use:

// note "long" vs "lang", a tiny typo in the variable name
$my_array_with_a_long_name = ['foo' => true];
array_key_exists('foo', $my_array_with_a_lang_name); // shows a warning
isset($my_array_with_a_lang_name['foo']); // returns false

You can also check for ordinal arrays:

$ord = ['a', 'b']; // equivalent to [0 => 'a', 1 => 'b']

array_key_exists(0, $ord); // true
array_key_exists(2, $ord); // false

Noticed that isset() has better performance than array_key_exists() as the latter is a function and the former a language construct.

Checking if a variable is an array

4

Due to the dynamic typing nature of PHP, sometimes you will need to determine if a variable is of type array. The is_array() function is the best method.

Example:

$variableA = 1337;
$variableB = [1337,42];

$isArrayVariableA = is_array($variableA);
// false

$isArrayVariableB = is_array($variableB);
// true

In functions, you can also do that by using type hints:

function foo(array $a) { ... }

which will result in a fatal error when the function parameter is not an array.

Filtering an array

4

In order to filter out values from an array and obtain a new array containing all the values that satisfy the filter condition, you can use the array_filter function.

Filtering non-empty values

The simplest case of filtering is to remove all "empty" values:

$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$non_empties = array_filter($my_array); // $non_empties will contain [1,2,3,4,5,6,7,8]; 

Filtering by callback

This time we define our own filtering rule. Suppose we want to get only even numbers:

$my_array = [1,2,3,4,5,6,7,8];

$even_numbers = array_filter($my_array, function($number) {
    return $number % 2 === 0;   
});

The array_filter function receives the array to be filtered as its first argument, and a callback defining the filter predicate as its second.

5.6

Filtering by index

A third parameter can be provided to the array_filter function, which allows to tweak which values are passed to the callback. This parameter can be set to either ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH, which will result in the callback receiving the key instead of the value for each element in the array, or both value and key as its arguments. For example, if you want to deal with indexes istead of values:

$numbers = [16,3,5,8,1,4,6];

$even_indexed_numbers = array_filter($numbers, function($index) {
    return $index % 2 === 0;
}, ARRAY_FILTER_USE_KEY);

Indexes in filtered array

Note that array_filter preserves the original array keys. A common mistake would be to try an use for loop over the filtered array:

<?php

$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$filtered = array_filter($my_array); 

error_reporting(E_ALL); // show all errors and notices

// innocently looking "for" loop
for ($i = 0; $i < count($filtered); $i++) {
   print $filtered[$i];
}

/*
Output:
1
Notice: Undefined offset: 1
2
Notice: Undefined offset: 3
3
Notice: Undefined offset: 5
4
Notice: Undefined offset: 7
*/

This happens because the values which were on positions 1 (there was 0), 3 (null), 5 (empty string '') and 7 (empty array []) were removed along with their corresponding index keys.

If you need to loop through the result of a filter on an indexed array, you should first call array_values on the result of array_filter in order to create a new array with the correct indexes:

$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$filtered = array_filter($my_array); 
$iterable = array_values($filtered);

error_reporting(E_ALL); // show all errors and notices

for ($i = 0; $i < count($iterable); $i++) {
   print $iterable[$i];
}

// No warnings!

Removing elements from an array

3

To remove an element inside an array, e.g. the element with the index 1.

$fruit = array("bananas", "apples", "peaches");
unset($fruit[1]);

This will remove the apples from the list, but notice that unset does not change the indexes of the remaining elements. So $fruit now contains the indexes 0 and 2.

For associative array you can remove like this:

$fruit = array('banana', 'one'=>'apple', 'peaches');

print_r($fruit);
/*
    Array
    (
        [0] => banana
        [one] => apple
        [1] => peaches
    )
*/

unset($fruit['one']); 

Now $fruit is

print_r($fruit);

/*
Array
(
    [0] => banana
    [1] => peaches
)
*/

Note that

unset($fruit);

unsets the variable and thus removes the whole array, meaning none of its elements are accessible anymore.

Checking if a value exists in array

2
$fruits = ['banana', 'apple'];

$foo = in_array('banana', $fruits);
// $foo value is true

$bar = in_array('orange', $fruits);
// $bar value is false

Looping Through an Array

2

There are several ways to loop through an array in PHP. You can take the standard approach using a for loop with an incrementer

$colors = ['red', 'yellow', 'blue', 'green'];
for($i = 0; $i < count($colors); $i++){
    echo 'I am the color ' . $colors[$i] . '<br>';
}

Or you can loop through items using a foreach loop

foreach($colors as $color){
    echo "I am the color $color<br>";
}

If you are using keys for your array you can access those keys using a foreach loop

<?php
$foods = ['healthy' => 'Apples', 'bad' => 'Ice Cream'];
foreach($foods as $key => $food){
    echo "Eating $food is $key";
}

Multiple Arrays

If you have two different arrays the same length e.g:

$people = ['Tim', 'Tony', 'Turanga'];
$food = ['chicken', 'beef', 'slurm'];

You can loop through both of them by getting the index of the first array and using it to call the other:

foreach($people as $index => $person) {
    echo $person . ' likes ' . $food[$index] . '.<br>';
}

Which will output:

Tim likes chicken.
Tony likes beef.
Turanga likes slurm.

Seperate arrays can only be looped through if they are the same length and also have the same key name. This means if you don't supply a key and they are numbered, you will be fine, or if you name the keys and put them in the same order in each array.

You can also use array_combine.

$combinedArray= array_combine($people, $food);
// $combinedArray = ['Tim' => 'chicken', 'Tony' => 'beef', 'Turanga' => 'slurm'];

Then you can loop through this by doing the same as before:

foreach($combinedArray as $person => $meal) {
    echo $person . ' wants to eat ' . $meal . '.<br>';
}

Which will echo out:

Tim wants to eat chicken.
Tony wants to eat beef.
Turanga wants to eat slurm.

Storing functions in arrays

2

There are 2 commonly harnessed methods when using this: Anonymous Functions & Defined Functions.

Anonymous Functions

5.3

Provided your PHP version is >= 5.3, you'll be able to store anonymous functions within arrays.

$myArray = array(
    'foo' => 'bar',
    'func' => function($elem) {
        echo $elem;
    }
);

Allowing you to call it the above function as required, even passing through defined variables.

$myArray['func']('I am a string....cool.');

Example/Demo


Defined Functions

4.4

There doesn't seem to be a "required PHP version" to run defined functions. Testing was done from 4.4.9 onwards and this functioned as required.

function myFunction($elem) {
    echo $elem;
}

$myArray = array(
    'foo' => 'bar',
    'func' => 'myFunction'
);

Allowing you to call it just as above in Anonymous Functions;

$myArray['func']('I am a string....cool.');

Example/Demo


There are various other ways you are able to call these functions if required, harnessing the built in PHP functions: call_user_func() and call_user_func_array().

call_user_func($myArray['func'], 'I am a string....cool.');

Notes/Limitations

Along with this ability to define & call methods like this come limitations.

  • You can not reference the parent array of the function. Meaning you can not do the following (as it will throw an error):
$myArray = array(
    'foo' => 'bar',
    'func' => function($elem) {
        echo $elem;
        print_r($myArray); // this will throw an error
    }
);

$myArray['func']('test');

This also means that you can not attempt to reference/include the parent array via ...function($elem) use($myArray) { .... This will throw the same "Undefined variable..." PHP notice.

If you do feel the need to reference the parent array, there are ways around this that end up defeating the purpose of something like this and littering your namespace.

  • These are valid callback methods and are filed in PHP's documentation under the callback pseudo-type. It is worth-while understanding these callback methods.

Adding element to start of array

1

Sometimes you want to add an element to the beginning of an array without modifying any of the current elements (order) within the array. Whenever this is the case, you can use array_unshift().

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Taken from the PHP documentation for array_unshift().

If you'd like to achieve this, all you need to do is the following:

$myArray = array(1, 2, 3);

array_unshift($myArray, 4);

This will now add 4 as the first element in your array. You can verify this by:

print_r($myArray);

This returns an array in the following order: 4, 1, 2, 3.

Since array_unshift forces the array to reset the key-value pairs as the new element let the following entries have the keys n+1 it is smarter to create a new array and append the existing array to the newly created array.

Example:

$myArray = array('apples', 'bananas', 'pears');
$myElement = array('oranges');
$joinedArray = $myElement;

foreach ($myArray as $i) {
  $joinedArray[] = $i;
}

Output ($joinedArray):

Array ( [0] => oranges [1] => apples [2] => bananas [3] => pears ) 

Eaxmple/Demo

Imploding an array into string

1

implode() combines all the array values but looses all the key info:

$arr = ['a' => "AA", 'b' => "BB", 'c' => "CC"];

echo implode(" ", $arr); // AA BB CC

Imploding keys can be done using array_keys() call:

$arr = ['a' => "AA", 'b' => "BB", 'c' => "CC"];

echo implode(" ", array_keys($arr)); // a b c

Imploding keys with values is more complex but can be done using functional style:

$arr = ['a' => "AA", 'b' => "BB", 'c' => "CC"];

echo implode(" ", array_map(function($key, $val) { 
    return "$key:$val"; // function that glues key to the value
}, array_keys($arr), $arr)); 

// Output: a:AA b:BB c:CC

Merge or concatenate arrays

1
$fruit1 = ['apples', 'pears'];
$fruit2 = ['bananas', 'oranges'];

$all_of_fruits = array_merge($fruit1, $fruit2);
// now value of $all_of_fruits is [0 => 'apples', 1 => 'pears', 2 => 'bananas', 3 => 'oranges']

Note that array_merge will change numeric indexes, but overwrite string indexes

$fruit1 = ['one' => 'apples',  'two' => 'pears'];
$fruit2 = ['one' => 'bananas', 'two' => 'oranges'];

$all_of_fruits = array_merge($fruit1, $fruit2);
// now value of $all_of_fruits is ['one' => 'bananas', 'two' => 'oranges']

array_merge overwrites the values of the first array with the values of the second array, if it cannot renumber the index.

You can use the + operator to merge two arrays in a way that the values of the first array never get overwritten, but it does not renumber numeric indexes, so you lose values of arrays that have an index that is also used in the first array.

$fruit1 = ['one' => 'apples',  'two' => 'pears'];
$fruit2 = ['one' => 'bananas', 'two' => 'oranges'];

$all_of_fruits = $fruit1 + $fruit2;
// now value of $all_of_fruits is ['one' => 'apples', 'two' => 'pears']

$fruit1 = ['apples', 'pears'];
$fruit2 = ['bananas', 'oranges'];

$all_of_fruits = $fruit1 + $fruit2;
// now value of $all_of_fruits is [0 => 'apples', 1 => 'pears']

Sorting an Array

1

There are several sort functions for arrays in php:

sort()

Sort an array in ascending order by value.

$fruits = ['Zitrone', 'Orange', 'Banane', 'Apfel'];
sort($fruits);
print_r($fruits);

results in

Array
(
    [0] => Apfel
    [1] => Banane
    [2] => Orange
    [3] => Zitrone
)

rsort()

Sort an array in descending order by value.

$fruits = ['Zitrone', 'Orange', 'Banane', 'Apfel'];
rsort($fruits);
print_r($fruits);

results in

Array
(
    [0] => Zitrone
    [1] => Orange
    [2] => Banane
    [3] => Apfel
)

asort()

Sort an array in ascending order by value and preserve the indecies.

$fruits = [1 => 'lemon', 2 => 'orange',  3 => 'banana', 4 => 'apple'];
asort($fruits);
print_r($fruits);

results in

Array
(
    [4] => apple
    [3] => banana
    [1] => lemon
    [2] => orange
)

arsort()

Sort an array in descending order by value and preserve the indecies.

$fruits = [1 => 'lemon', 2 => 'orange',  3 => 'banana', 4 => 'apple'];
arsort($fruits);
print_r($fruits);

results in

Array
(
    [2] => orange
    [1] => lemon
    [3] => banana
    [4] => apple
)

ksort()

Sort an array in ascending order by key

$fruits = ['d'=>'lemon', 'a'=>'orange', 'b'=>'banana', 'c'=>'apple'];
ksort($fruits);
print_r($fruits);

results in

Array
(
    [a] => orange
    [b] => banana
    [c] => apple
    [d] => lemon
)

krsort()

Sort an array in descending order by key.

$fruits = ['d'=>'lemon', 'a'=>'orange', 'b'=>'banana', 'c'=>'apple'];
krsort($fruits);
print_r($fruits);

results in

Array
(
    [d] => lemon
    [c] => apple
    [b] => banana
    [a] => orange
)

natsort()

Sort an array in a way a human being would do (natural order).

$files = ['File8.stack', 'file77.stack', 'file7.stack', 'file13.stack', 'File2.stack'];
natsort($files);
print_r($files);

results in

Array
(
    [4] => File2.stack
    [0] => File8.stack
    [2] => file7.stack
    [3] => file13.stack
    [1] => file77.stack
)

natcasesort()

Sort an array in a way a human being would do (natural order), but case intensive

$files = ['File8.stack', 'file77.stack', 'file7.stack', 'file13.stack', 'File2.stack'];
natcasesort($files);
print_r($files);

results in

Array
(
    [4] => File2.stack
    [2] => file7.stack
    [0] => File8.stack
    [3] => file13.stack
    [1] => file77.stack
)

shuffle()

Shuffles an array (sorted randomly).

$array = ['aa', 'bb', 'cc'];
shuffle($array);
print_r($array);

As written in the description it is random so here only one example in what it can result

Array
(
    [0] => cc
    [1] => bb
    [2] => aa
)

usort()

Sort an array with a user defined comparison function.

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

$array = [3, 2, 5, 6, 1];
usort($array, 'compare');
print_r($array);

results in

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

uasort()

Sort an array with a user defined comparison function and preserve the keys.

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

$array = ['a' => 1, 'b' => -3, 'c' => 5, 'd' => 3, 'e' => -5];
uasort($array, 'compare');
print_r($array);

results in

Array
(
    [e] => -5
    [b] => -3
    [a] => 1
    [d] => 3
    [c] => 5
)

uksort()

Sort an array by keys with a user defined comparison function.

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

$array = ['ee' => 1, 'g' => -3, '4' => 5, 'k' => 3, 'oo' => -5];

uksort($array, 'compare');
print_r($array);

results in

Array
(
    [ee] => 1
    [g] => -3
    [k] => 3
    [oo] => -5
    [4] => 5
)

Split array into chunks

1

array_chunk() splits an array into chunks

Let's say we've following single dimensional array,

$input_array = array('a', 'b', 'c', 'd', 'e');

Now using array_chunk() on above PHP array,

$output_array = array_chunk($input_array, 2);

Above code will make chunks of 2 array elements and create a multidimensional array as follow.

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

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

    [2] => Array
        (
            [0] => e
        )

)

If all the elements of the array is not evenly divided by the chunk size, last element of the output array will be remaining elements.


If we pass second argument as less then 1 then E_WARNING will be thrown and output array will be NULL.

ParameterDetails
$array (array)Input array, the array to work on
$size (int)Size of each chunk ( Integer value)
$preserve_keys (boolean) (optional)If you want output array to preserve the keys set it to TRUE otherwise FALSE.

Split string into Array

1

A string containing several parts of text that are separated by a common character can be split into parts with the explode function.

$fruits = "apple,pear,grapefruit,cherry";
print_r (explode(",",$fruits)); // ['apple', 'pear', 'grapefruit', 'cherry']

The method also supports a limit parameter that can be used as follow:

$fruits= 'apple,pear,grapefruit,cherry';

// 0limit
print_r(explode(',',$fruits,0)); // ['apple,pear,grapefruit,cherry']

// positive limit
print_r(explode(',',$fruits,2)); // ['apple', 'pear,grapefruit,cherry']

// negative limit 
print_r(explode(',',$fruits,-1)); // ['apple', 'pear', 'grapefruit']

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If the limit parameter is negative, all components except the last -limit are returned.

If the limit parameter is zero, then this is treated as 1.

Whitelist only some array keys

1

When you want to allow only certain keys in your arrays, especially when the array comes from request parameters, you can use array_intersect_key together with array_flip.

$parameters = ['foo' => 'bar', 'bar' => 'baz', 'boo' => 'bam'];
$allowedKeys = ['foo', 'bar'];
$filteredParameters = array_intersect_key($parameters, array_flip($allowedKeys));

// $filteredParameters contains ['foo' => 'bar', 'bar' => 'baz]

If the parameters variable doesn't contain any allowed key, then the filteredParameters variable will consist of an empty array.

Array intersection

0

The array_intersect function will return an array of values that exist in all arrays that were passed to this function.

$array_one = ['one', 'two', 'three'];
$array_two = ['two', 'three', 'four'];
$array_three = ['two', 'three'];

$intersect = array_intersect($array_one, $array_two, $array_three);
// $intersect contains ['two', 'three']

Array keys are preserved. Indexes from the original arrays are not.

array_reduce

0

array_reduce reduces array into a single value. Basically, The array_reduce will go through every item with the result from last iteration and produce new value to the next iteration.

Usage: array_reduce ($array , function($carry,$item){...},$defaul_value_of_first_carry)

  • $carry is the result from the last round of iteration.
  • $item is the value of current position in the array.

Sum of array

$result=array_reduce([1,2,3,4,5],function($carry,$item){
    return $carry+$item;
});

result:15

The largest number in array

$result=array_reduce([10,23,211,34,25],function($carry,$item){
        return $item>$carry?$item:$carry;
});

result:211

Is all item more than 100

$result=array_reduce([101,230,210,341,251],function($carry,$item){
        return $carry&&$item >100;
},true); //default value must set true

result:true

Is any item less than 100

$result=array_reduce([101,230,21,341,251],function($carry,$item){
        return $carry||$item <100;
},false);//default value must set false

result:true

Like implode($array,$piece)

$result=array_reduce(["hello","world","PHP","language"],function($carry,$item){
        return !$carry?$item:$carry."-".$item ;
});

result:"hello-world-PHP-language"

if make a implode method, the source code will be :

function implode_method($array,$piece){
    return array_reduce($array,function($carry,$item) use ($piece) {
            return !$carry?$item:$carry.$piece.$item ;
    });
}

$result=implode_method(["hello","world","PHP","language"],"-");

result:"hello-world-PHP-language"

Combining two arrays (keys from one, values from another)

0

The following example shows how to merge two arrays into one associative array, where the key values will be the items of the first array, and the values will be from the second:

$array_one = ['key1', 'key2', 'key3'];
$array_two = ['value1', 'value2', 'value3'];

$array_three = array_combine($array_one, $array_two);
var_export($array_three);

/* 
    array (
      'key1' => 'value1',
      'key2' => 'value2',
      'key3' => 'value3',
    )
*/

Transform elements with callbacks

0

The function array_map gives an elegant way to process every element with a callback function. This function will return a modified array:

$salaries = array ('John' => 100, 'James' => 110, 'Peter' => 120, 'Mary' => 105);
// Add 10 to every people's salary
$newSalaries = array_map(function($value) { return $value + 10; }, $salaries);
var_dump($newSalaries);

Output:

array(4) {
    ["John"]  => int(110)
    ["James"] => int(120)
    ["Peter"] => int(130)
    ["Mary"]  => int(115) 
}

If we need to process both values and keys we use another function array_walk. This function changes passed array:

// Double the salary of people whose names start with 'J'
array_walk($salaries, function(&$value, $key) { 
    $value = (substr($key, 0, 1) == 'J') ? 2 * $value : $value; 
});
var_dump($salaries);

Output:

array(4) {
    ["John"]  => int(200)
    ["James"] => int(220)
    ["Peter"] => int(120)
    ["Mary"]  => int(105)
}

Topic Outline