PHP

PHP array functions

A lot of time we need to perform some action in our code e.g sorting of an array, and many times it happens that we write a new function for that, because we were too lazy to search if this function already exists or not. So I thought of compiling a list which gives you access to many such functions. However I will not compose the whole list at once but I will keep adding functions in this blog post :

  1. Change the case of all keys in an array 
array array_change_key_case(array $array [, int $case = CASE_LOWER])

Returns an array with all keys from array lowercased or uppercased. Numbered indices are left as is

Parameter

array
The array to work on

case
Either UPPER_CASE or LOWER_CASE (default)

<?php
$inputArray = ['FirsT' => 1, 'SecONd' => 2];
print_r(array_change_key_case($inputArray, CASE_UPPER));
?>

The above example will output :

Array
(
     [FIRST] => 1
     [SECOND] => 2
)

2. Split an array into chunks 

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

Chunks an array into arrays with size elements. The last chunk may contain less than size element. Useful in scenarios where you have to process mass data or you have to supply an array to generate html rows (2/4/6 results in a row)

Parameters

array
The array to work on

size
The size of each chunk

preserve_keys
When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically.

Example

<?php
$inputArray = ['a', 'b', 'c', 'd', 'e'];
print_r(array_chunk($inputArray, 2));
print_r(array_chunk($inputArray, 2 , true));
?>

The above example will give the following output :

Array
(
    [0] => Array
               (
                    [0]  => a
                    [1] => b
              )
   [1] => Array
              (
                   [0] => c
                   [1] => d
              )
   [2] => Array
              (
                   [0] => e
              )
)
Array
(
    [0] => Array
               (
                    [0]  => a
                    [1] => b
              )
   [1] => Array
              (
                   [2] => c
                   [3] => d
              )
   [2] => Array
              (
                   [4] => e
              )
)