PHP Complete Cheatsheet! Everything You Need To Know

PHP Cheatsheet

Table of contents for this Cheat sheet: An overview of every main PHP array functionHow can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?How could you include a custom function for every single time PHP runs?How do you access the php://input stream?How do you launch the PHP interactive shell?How do you run a PHP script from the command line?How does PHP compare objects?How to add comments in PHPHow to check if a object has a static variable defined?How to check if two strings are anagrams in PHP?How to convert a string to an array of it's characters in PHP?How to destroy or remove a cookie in PHPHow to Extract Query String (from a URL) Into an Associative Array in PHPHow to find out which php.ini file PHP is using?How to find the 2nd most common item in an array?How to find the intersection (same values) from two arrays?How to manually write your own pagination in PHPHow to output (echo/print) content in PHPHow to pick what array_intersect function to use in PHP?How to query mysql using PDO in PHP?How to replace whitespace with a single spaceHow to reverse htmlentities() / What is the opposite of htmlentities()?How to set infinite execution time in a PHP scriptHow to sort an array of dates and times?How to use Anonymous classes in PHP 7?How to view all installed PHP modules?Is multiple inheritance supported in PHP?PHP Date commonly used formatsWhat are generators in PHP, and how do they compare to arrays?What are PHP's PSRs?What are the main error types in PHPWhat are the predefined variables in PHP?What are the SPL data structuresWhat are the SPL Iterators in PHP?What does 'final class' and 'final function' (final method) mean in PHP?What does PEAR stand for?What is camel case?What is snake case?What is the difference between empty(), isset(), != null, is_null() in PHPWhat is the max size, by default, of GET variables?What is the null coalescing operator in PHP7?What is the spaceship operator (<=>) in PHP?When is __destruct called in 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] => 2
)

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] => 5
    [1] => 3
    [2] => 4
    [3] => 1
    [4] => 2
)

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
        )

)
View More Details (and 6 discussions about this topic) Here...

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

There are a couple of ways to achieve this, both very simple.

The most simple is to use ctype_alnum(). This function has been in PHP since PHP4. The following code would output 'all passed', as all three strings are alphanumeric

  1.             if( ctype_alnum("aBcDeFg1234") &&  ctype_alnum("aaa") &&  ctype_alnum("123") ) {
  2.               echo "all passed";
  3.             }

If you need a bit more flexibility, then you could use regex:

  1. return preg_match('/[^a-z0-9]/i', $input);

In the example above, it adds no real advantage and is slower than ctype_alnum so I would recommend just using ctype_alnum.

If you need to check if alpha numeric, but include underscores and dash (hyphen), then you can use the following regex check:

  1. if(preg_match('/[^a-z_\-0-9]/i', $input))
  2. {
  3. return true;
  4. }
  5. return false;

(Both of these are case insensitive, thanks to the i modifier)

You could also do this:

  1. preg_match('/^[\w-]+$/',$input)

Or even [:alnum:]

  1. preg_match("/[^[:alnum:]\-_]/",$str)
View More Details (and 10 discussions about this topic) Here...

How could you include a custom function for every single time PHP runs?

There are probably a few ways to do this, but one simple way would be to put your function in a file in /somedir/something.php. Then update php.ini and set auto_prepend_file = /somedir/something.php.

If you want to use a package (via composer) on all of your scripts you could also do something like composer global require THEPACKAGE/NAMEHERE, then do auto_prepend_file = ${HOME}/.composer/vendor/autoload.php

I would not recommend doing this though! The setup will work only on your current machine, and would cause problems with debugging or getting your scripts to work the same on other machines. I have very rarely used auto_prepend_file, and every time I have it has caused problems with deployment to other servers or for testing.
View More Details (and 8 discussions about this topic) Here...

How do you access the php://input stream?

The php://input contains the raw data from a POST request, after all of the HTTP headers. You can think of $_POST as the same data (...sometimes) that has been parsed into an array. php://input gets the raw data. The stream can be accessed in the following way:

  1. $val = file_get_contents("php://input");
View More Details (and 8 discussions about this topic) Here...

How do you launch the PHP interactive shell?

As of PHP 5.1.0, the CLI SAPI provides an interactive shell. To use it, enter the following command at a command line:

  1. php -a

If you run 'php -a' and just see 'Interactive mode enabled', but nothing happens when you type something and hit enter then this means that the interactive shell isn't activated for your installation of PHP. You must have the readline module installed (check if you do by running php -m | grep -i readline).

If you see 'Interactive mode enabled', then after typing in your PHP code (don't forget the opening PHP tag), press ctrl+d

$ php -a
Interactive mode enabled

<?php echo "hello, world" . rand(); ?>

hello, world665146942

Note: in the above output, I hit ctrl+d in the 2nd to last line, then it executed the PHP code that I typed and echoed the output.

View More Details (and 3 discussions about this topic) Here...

How do you run a PHP script from the command line?

Just run php your-file.php.

php your_file.php

And it will execute the PHP file.

View More Details (and 6 discussions about this topic) Here...

How does PHP compare objects?

If two objects are compared with ==, then it will check if:

1) - they are two instances of the same type of class

2) - they have the same properties

3) - and those properties have the same values

  1. $a = new SomeClass();
  2. $a->something = 123;
  3.  
  4. $b = new SomeClass();
  5. $b->something = 123;
  6.  
  7. return $a == $b; // true

If two objects are compared with ===, then PHP will return true only if both variables are pointing to the exact same object (the same instance of the object). Remember that objects are always passed by value.

For example, the following will return true:

  1. $a = new SomeClass();
  2. $a->something = 123;
  3. $b = $a; // $a and $b point to the exact same instance
  4.  
  5. return $a === $b; // true

However, the following (using ===) will return false. If the check was with == then it would return true, as the class type/properties/values are the same

  1. $a = new SomeClass();
  2. $a->something = 123;
  3.  
  4. $b = new SomeClass(); // different instance
  5. $b->something = 123;  // same values
  6.  
  7. return $a === $b; // false
View More Details (and 5 discussions about this topic) Here...

How to add comments in PHP

Comments are parts of the code that don't really do anything (some exceptions) apart from be read by humans.

There are a few ways to add comments in PHP.

1: // - single line comments

  1. <?php
  2.         echo 'hello';
  3.         // this is a comment
  4.         echo 'world';

2: # - single line comments

  1. <?php
  2.         echo 'hello';
  3.         # this is a comment
  4.        echo 'world';

3: /* ... */ - multi line comments

  1. <?php
  2.         echo 'hello';
  3.         /* this is a comment
  4.         echo 'world';
  5.  
  6.         */
  7.         echo 'the end';

The only times that comments have any effect on the code that is processed is when some scripts scan 'DocComment'. A DocComment is one that starts like this /** ... */.

View More Details (and 3 discussions about this topic) Here...

How to check if a object has a static variable defined?

If you have an object and you need to check if it has a const SOME_CONSTANT = 'foo' set, then you can use defined in the following way:

  1.         class ExampleClass {
  2.             const CONST_THAT_DOES_EXIST = 9;
  3.  
  4.             function does_it_have_const() {
  5.             // late static binding:
  6.                 var_dump( defined('static::CONST_THAT_DOES_EXIST') );
  7.                 var_dump( defined('static::CONST_THAT_DOES_NOT_EXIST') );
  8.  
  9.                 // or use self
  10.                 var_dump( defined('self::CONST_THAT_DOES_EXIST') );
  11.             }
  12.  
  13.         }
View More Details (and 11 discussions about this topic) Here...

How to check if two strings are anagrams in PHP?

This is a classic simple programming question. There are several ways to approach this problem. Here is one solution:

The comparison function:

  1. function is_anagram($a, $b)
  2. {
  3.  
  4.     if (strlen($a) != strlen($b)) {
  5.         // if not same size then they definitely aren't
  6.         return false;
  7.     }
  8.  
  9. // turn 'foobar' into ['f', 'o', 'o', 'b', 'a', 'r']
  10. $a_chars = str_split($a);
  11. $b_chars = str_split($b);
  12.  
  13. // sort them...
  14. sort($a_chars);
  15. sort($b_chars);
  16.  
  17. // check if they're exactly the same...
  18. return $a_chars === $b_chars;
  19.  
  20. // another way to do this that someone emailed me about, which is much more simple:
  21. // return (count_chars($a, 1) == count_chars($b, 1))
  22.  
  23.  
  24. }

Let's write some tests

  1. $anagrams = [
  2.  
  3.     // $a, $b, $is_valid_anagram
  4.  
  5.         ["asdf", "asdf", true],
  6.         ["asdf", "fdsa", true],
  7.         ["asdfasdf", "asdfasdf", true],
  8.         ["a", "a", true],
  9.         ["a", "b", false],
  10.         ["aaa", "aaa", true],
  11.         ["aaa", "aa", false],
  12.         ["aaaa", "abab", false],
  13.         ["qwerty", "asdfg", false]
  14.  
  15. ];

And now let's go through each one.

  1. foreach ($anagrams as $anagram) {
  2.  
  3.     [$a, $b, $is_valid_anagram] = $anagram;
  4.  
  5.     $result = is_anagram($a, $b);
  6.     $result_message = $result ? "Is an anagram" : "Is not an anagram";
  7.  
  8.     if ($result != $is_valid_anagram) {
  9.         throw new \Exception("The anagram function returned an incorrect result for $a and $b");  // this doesn't happen with our function! :)
  10.     }
  11.     var_dump("[$a] and [$b] $result_message");
  12.  
  13. }
"Our function said that [asdf] and [asdf] Is an anagram, which is correct"
"Our function said that [asdf] and [fdsa] Is an anagram, which is correct"
"Our function said that [asdfasdf] and [asdfasdf] Is an anagram, which is correct"
"Our function said that [a] and [a] Is an anagram, which is correct"
"Our function said that [a] and [b] Is not an anagram, which is correct"
"Our function said that [aaa] and [aaa] Is an anagram, which is correct"
"Our function said that [aaa] and [aa] Is not an anagram, which is correct"
"Our function said that [aaaa] and [abab] Is not an anagram, which is correct"
"Our function said that [qwerty] and [asdfg] Is not an anagram, which is correct"

BTW, not sure about how the [$a, $b, $is_valid_anagram] = $anagram; line works? See my blog post about array destructuring in PHP 7.

View More Details (and 4 discussions about this topic) Here...

How to convert a string to an array of it's characters in PHP?

If you want to get an array of (single) letters from a string, it is easy in PHP! Here is how to do it:

Use str_split() to get a text string's characters as an array

  1. $input = "asdfgh";
  2.         $array = str_split($input); // ['a','s','d','f','g','h']
View More Details (and 4 discussions about this topic) Here...

How to destroy or remove a cookie in PHP

To remove a cookie, you should set its expiry to a date in the past.

  1. setcookie("the_cookie_name", "", time()-(60*60*24*7));
  2. // or also set the path, if it was set with a path:
  3. setcookie("the_cookie_name", "", time()-(60*60*24*7),"/");

And then the next time the user loads a page (or makes a request), their browser will remove the cookie.

You should also clear PHP's 'copy' of the cookie:

  1. unset($_COOKIE["the_cookie_name"]);
View More Details (and 10 discussions about this topic) Here...

How to Extract Query String (from a URL) Into an Associative Array in PHP

If you have a query string (such as ?a=foo&b=bar) and want to convert that into a PHP array, this is how to do it.

Let's take a full example, where we begin with a URL, get the query string part of it, then convert that into an array.

  1.         $url = "https://example.com/?foo=bar&foo2=bar2";
  2.         $parsed_url = parse_url($url);
  3.         // $parsed_url is an array of the parts of the URL, such as host, query_string, path, etc
  4.         $query_string = $parsed_url["query"];
  5.         // $query_string is now foo=bar&foo2=bar2
  6.  
  7.         // now let's convert that into an array:
  8.         // don't forget the 2nd param - it is the variable where the array will be
  9.          parse_str($query_string,$array_of_query_string);
  10.  
  11.  
  12.         return $array_of_query_string;
array(2) {
      ["foo"]=> string(3) "bar"
      ["foo2"]=> string(4) "bar2"
      }
View More Details (and 12 discussions about this topic) Here...

How to find out which php.ini file PHP is using?

To find out which php.ini file (and its full file path) just run the following command:

php --ini

Which will output something like this:

$ php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

If you need to check from within a PHP script, you can either put this code in (if it isn't public facing) and search for 'Loaded configuration file':

  1. <?php phpinfo(); ?>

Or run:

  1. <?php var_dump(php_ini_loaded_file()); ?>

See also: php_ini_scanned_files()

View More Details (and 9 discussions about this topic) Here...

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

Let's say you have an array with values of people's names. You want to find the 2nd most common name. How would you do this?

First you want to get a count of all values. Luckily PHP has this built in.

  1. $names = [
  2.  
  3.  
  4.     'Bart',
  5.     'Lisa',
  6.     'Amy',
  7.     'Philip',
  8.     'Bart',
  9.     'Fred',
  10.     'Philip',
  11.     'Bart',
  12.     'Fred',
  13.     'Leela',
  14.     'Barney',
  15.     'Philip',
  16.     'Bart',
  17.     'Barney',
  18.     'Ned',
  19.     'Bart'
  20.  
  21.     ];
  22.  
  23. $what_position_we_want = 2;
  24. $vals = array_count_values($names);
  25. // var_dump($vals) = ['Bart' => 5, 'Lisa' => 1, 'Amy' => 1, 'Philip' => 3, ...]

So now that we have an array where the keys are the names, and the values are the count of how many times they appear, we just need to sort it and pick the 2nd item.

To pick the 2nd element of the array, we need to use array_keys() so the array is numerically indexed...

  1. // we want it in reverse (so we can do $vals[1] to get the 2nd item)
  2. // rsort($vals) would sort it (in reverse), however it assigns new keys (we need to key to know what name it is!)
  3. // so we have to do arsort()
  4. arsort($vals);
  5.  
  6. // we need to get an array with the values (names) keyed by id, so we can do $keys[1]
  7. $keys = array_keys($vals);
  8.  
  9. echo "The $what_position_we_want most popular name is: " . $keys[$what_position_we_want-1];
The 2 most popular name is: Philip
View More Details (and 12 discussions about this topic) Here...

How to find the intersection (same values) from two arrays?

If you have two (or more) arrays with various values, how do you find the values from the 1st array that are also in the 2nd (and others) array? Use the intersect functions.

PHP has a nice collection of array functions - one of which is array_intersect. You can use it to solve this problem.

  1.        $array1 = ['apple','banana','grape','orange'];
  2. $array2 = ['cake', 'apple', 'toast', ];
  3.  
  4. $vals_in_both_arrays =  array_intersect($array1,$array2);

Which outputs an array with the single item in both arrays: ['apple'].


What if you need to compare the keys and values?

Then use array_intersect_assoc() which will compare both keys and values.

  1.  $array1 = ["aa" => "a",
  2.                     "bb" => "b",
  3.                     "cc" => "c",
  4.                     "dd" => "d"
  5.                 ];
  6.  
  7.         $array2 = [
  8.  
  9.             "dd" =>"d", // same as above
  10.             "foo" => "bar",
  11.             "bb" => "not_b",
  12.             "cc" => "c", //same as above
  13.             "aa" => "not_a",
  14.  
  15.  
  16.             ];
  17.  
  18.  
  19.         $same = (array_intersect_assoc($array1,$array2));
array:2 [
  "cc" => "c"
  "dd" => "d"
]

If you just want to compare the keys, then use array_intersect_keys().

View More Details (and 6 discussions about this topic) Here...

How to manually write your own pagination in PHP

If you use a framework such as Laravel you almost always have some pagination features built in. Here is how to manually write out your own pagination feature in some simple to follow PHP.

For this code I'll still be using Eloquent, part of Laravel. It would be easy to write out the SQL too, so I've included that as well.

Let's begin by working out how many items we have in total

First we need to know the total number of rows that we are working with, and decide how many we will show per page.

  1. $count = BlogPost::count();
  2. $per_page = 15;

This would be the same as: select count(*) as c from blog_posts

Calculate how many pages there will be:

  1. $pages = ceil($count / $per_page);

The ceil() function will round up to the next full integer. So if $count/$per_page was 4.1, it would return 5.

Also, get the current page!

We need to decide what page the user is currently on. The first page would be page 1 (so be sure to remember to hard code that, even if $_GET['page'] (or whatever you use) is not set. I will hard code it in though...

  1. $current_page = (int) 8; // ensure it is an integer!
  2. if ($current_page < 1) {
  3.     $current_page = 1;
  4. }
  5. if ($current_page>$pages) {
  6.     $current_page = $pages;
  7.     // or really, do a HTTP temporary redirect to that page
  8. }

Here we set the current page (but you could replace the 8 with $_GET['page'] ?? 1 (which will be the value of 'page' in the url (for example yoursite.com/your-script.php?page=123) or default to 1.

If the selected page is greater than the number of pages then you should do something like show 404 error, just show the max page's content (which is what the code above does), redirect to another page, or just show 'nothing found' (like a soft 404 error).

Oh, and of course you want to check that the current page is no smaller than 1!

Now you want to decide how many items 'along' you want to start from... (LIMIT startfromhere, takethismany, or LIMIT takethismany OFFSET startfromhere).

  1. $current_page_from = ($current_page - 1) * $per_page;

Putting it all together

Now we have everything we need!

If you are using a ORM like eloquent, you can do something like this:

  1. $rows = BlogPost::orderBy("id", "asc")->skip($current_page_from)->take($per_page)->get()

This would generate something like this (for page 8, 15 per page): select * from `interview_question_q_and_as` order by `id` asc limit 15 offset 105.

The reason I am focusing on providing Eloquent code and not really playing with SQL direct is because this is a beginners topic (pagination), and I really don't recommend beginners start off with direct SQL as there are so many SQL injection attacks that you will probably leave yourself open for attack with. Always use prepared statements, don't put any variables direct in SQL. I'll have a guide soon explaining everything....

Pagination links

Don't forget to include pagination links. This will simply loop through them all. You might want to modify it to show prev/next links. If you have a a.active { font-weight:bold;} css rule, the current page will be highlighted.

  1. for($i=1;$i<=$pages;$i++) {
  2.     $active = ($i === $current_page) ? " class='active' " : "";
  3.     echo "<a href='?page=$i' $active>Page $i</a> ";
  4. }

How to do it in Laravel's Eloquent

  1. // it automatically works out what page you are on
  2. $posts = BlogPost::paginate(15);
  3.  
  4. foreach($posts as $post) {
  5.     // cycle through the posts
  6. }
  7.  
  8.  
  9. // creating the clickable links...
  10.  echo $posts->appends( [] )->links();

You can use the array in appends() to automatically include any url parameters.

(for example, if your url was /?page=3&search_for=ducks, you should do appends(['search_for']) to ensure that it gets included in your pagination links.

View More Details (and 5 discussions about this topic) Here...

How to output (echo/print) content in PHP

There are several ways to output data/content. I might have forgotten about one of them

1) A php file with any content apart from <?php . Without the PHP opening tag, everything else will be echoed out.

2) echo 'some text'; - a simple echo

3) print ('some text'); - similar to echo

4) <?='some text':?> or <?=$a_variable:?>

5) and via functions such as print_r(12345) or var_dump($something)

What is the difference between echo and print in PHP?

There isn't much difference. The only two differences are that echo does not return any value, and can take multiple arguments (echo($a,$b,$b). print() returns a value of 1 and can only take one parameter. Years ago echo() used to be a bit faster, now it would be so insignificant that it is not worth even thinking about which is faster..

View More Details (and 8 discussions about this topic) Here...

How to pick what array_intersect function to use in PHP?

So you want to do an intersect, but not sure which PHP function to use? There are around 8 variations on the array intersection function built into PHP. Here is a guide for helping your pick which one to use!

The main array intersect functions in PHP

The basic idea of all of them is that it will return an array of all values from the first array that are also in the other arrays.

The differences between them are based on the following:

  • If the user provides the compare function (u)
  • If it will compare keys (assoc), values, or both
array_intersect()

This is the main one, I guess!

This will return an array with all values from $array1 that are present in all the others. It just compares the values, ignoring the keys

array_intersect_assoc()

Same as above, but it checks both values and keys

array_intersect_uassoc()

It checks the keys (via user supplied function) and values. The values are checked by normal comparison, but they keys are checked by a user supplied function.

array_intersect_key()

Returns array of everything from the first array which have keys in the other arrays.

array_intersect_ukey()

Same as above, but the comparison function for the keys is provided by the user.

array_uintersect()

Same as array_intersect() - but the user provides the comparison function for comparing the values

array_uintersect_assoc()

Same as array_uintersect() (above), but the user provided function checks the keys

array_uintersect_uassoc()

And in this function it is the two above combined. The user provides 2 comparison functions (one for keys, one for values), and it will check against both of those.

I've been coding professionally for years in PHP, and I still have to double check which one to use every time...

View More Details (and 3 discussions about this topic) Here...

How to query mysql using PDO in PHP?

Years ago you used to see mysql_... functions everywhere. This has been (fortuantely) replaced by first the mysqli functions and more recently the object oriented way of PDO. Using PDO you can easily swap between database drivers (Mysql, Postgre, SQLite, etc). Here is how to connect to a mysql database, and then how to query it using PDO.

This also applies to mariadb

Connecting to MySQL with PDO in PHP

You should wrap this in a try/catch to handle a database connection error.

  1.   try {
  2.     $host = "your host";
  3.     $dbname = "your_database";
  4.     $user = "your_user";
  5.     $pass = "qwerrtyuiop12345678";
  6.  
  7.     $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
  8.   }
  9.   catch(PDOException $e) {
  10.       echo  $e->getMessage(); // handle this better, this is just for the demo!
  11.   }

How to query the database

With PDO you don't have to think about escaping data. Every query should be 'prepared', then you can bind variables to placeholders. If you follow this example it should make sense.

In this example, we will do an insert and create a blog post with the following data:

  1. $title = "Blog post title";
  2. $post_body = "Blog post body";
  3. $status = "published_status";

Unnamed placeholders

  1.   $prepared_statement = $dbh->("INSERT INTO blog_posts (title, post_body, status) values (?, ?, ?)");

These are indexed, starting at 1.

  1. $prepared_statement->bindParam(1, $title);
  2. $prepared_statement->bindParam(2, $post_body);
  3. $prepared_statement->bindParam(3, $status);

And then you execute it:

  1. $prepared_statement->execute();

Named placeholders

You can also used named placeholders. They don't have to match anything else in the sql statement.

Although you will see a : before their names (such as :title) here and in most code, they aren't required. But they are a common convention that you should follow!

  1.   $prepared_statement = $dbh->("INSERT INTO blog_posts (title, post_body, status) values ( :title, :body, :post_status )");

Now that we have prepared the statement and used some named params, we need to bind them:

  1. $prepared_statement->bindParam(":title", $title);
  2. $prepared_statement->bindParam(":body", $post_body);
  3. $prepared_statement->bindParam(":post_status", $status);

And then you execute it:

  1. $prepared_statement->execute();

Alternative ways to do this:

You can also pass an array to ->execute with an array:

  1.   $prepared_statement = $dbh->("INSERT INTO blog_posts (title, post_body, status) values ( :title, :body, :post_status )");
  2.   $prepared_statement->execute([
  3.       "title" =>"my new blog post",
  4.       "body" => "Welcome to my new blog",
  5.       "post_status" => "published_status",
  6.   ]);
  7.   // or
  8.   $prepared_statement = $dbh->("INSERT INTO blog_posts (title, post_body, status) values ( ?,  ?, ? )");
  9.   $prepared_statement->execute([
  10.       "my new blog post",
  11.       "Welcome to my new blog",
  12.       "published_status",
  13.   ]);

An important thing to note about bindParam...

If you look at the method structure:

bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )

You might notice the second parameter. It is &$variable - by reference. So if you did this:

  1.     $title = "title 1";
  2.   $prepared_statement = $dbh->("INSERT INTO blog_posts (title) values ( :title)");
  3.   $prepared_statement->bindParam(1, $title);
  4.   $title = "updated title here";
  5.   $prepared_statement->execute();?>

Then a new row would be inserted with "updated title here".

Why? because sent $title to bindParam, which saves the reference. You then update $title to "updated title here", so when you run ->execute() it uses whatever value is in $title, which is obviously the updated value.

Use bindValue() to avoid this issue.

How to get rows from the database?

By default PDO will return an array indexed by both column name and number (e.g. [1=> "some blog title", 'blog_title' => "some blog title", 2 => "some blog post body" , "post_body" => "some blog post body"].

There are a few ways to change this. You can use $statement->setFetchMode(...) (or $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);) to change this behaviour.

If I want to just work with an array I will normally use PDO::FETCH_ASSOC. The fetchObject method is nice too - it fetches the next row and returns it as an object. You can define what class it will create, so you can set it up to return model objects.

But anyway, on to some examples.

SELECT queries...

I am going to use the direct ->query() here, avoiding the binding and execute.

  1. $query = $dbh->query("SELECT * FROM blog_posts");
  2. foreach ($query as $row)
  3. {
  4.     var_dump($row);
  5. }

But I could also do this:

  1. $blog_post_id=123;
  2. $statement = $dbh->prepare("SELECT * FROM blog_posts WHERE id = ?");
  3. $statement->execute([ $blog_post_id] );
  4.  
  5. //get one row:
  6. $row = $statement->fetch();
  1. $category_id=22;
  2. $statement = $dbh->prepare("SELECT * FROM blog_posts WHERE category_id = ?");
  3. $statement->execute([ $category_id] );
  4.  
  5. // get all:
  6. $rows = $statement->fetchAll();

Update and delete

You can run these in a similar manner.

Delete SQL statement with PDO

  1. $category_id=22;
  2. $statement = $dbh->prepare("DELETE FROM blog_posts WHERE category_id = ?");
  3. $statement->execute([ $category_id] );

Update SQL statement with PDO

  1. $id=22;
  2. $new_title = "foobar";
  3. $statement = $dbh->prepare("UPDATE blog_posts set title = ? WHERE id = ?");
  4. $statement->execute([ $title, $id] );
View More Details (and 4 discussions about this topic) Here...

How to replace whitespace with a single space

If you want to replace multiple whitespace characters (multiple spaces, new lines, etc) with just a single space, use this:

  1. $code = preg_replace('!\s+!', ' ', $code);
View More Details (and 11 discussions about this topic) Here...

How to reverse htmlentities() / What is the opposite of htmlentities()?

If you need to reverse or undo htmlentities() you can use the following function to do so in PHP:

  1. html_entity_decode($var)

This will convert HTML entities to their corresponding characters.

Info about html_entity_decode()

There are a few flags that you can use (as the 2nd parameter):

Constant NameDescription
ENT_COMPATWill convert double-quotes and leave single-quotes alone.
ENT_QUOTESWill convert both double and single quotes.
ENT_NOQUOTESWill leave both double and single quotes unconverted.
ENT_HTML401 Handle code as HTML 4.01.
ENT_XML1 Handle code as XML 1.
ENT_XHTML Handle code as XHTML.
ENT_HTML5 Handle code as HTML 5.

You can set what encoding to use by passing an option to the 3rd parameter. By default it will use the default_charset php setting.

The following character sets are supported:

CharsetAliasesDescription
ISO-8859-1ISO8859-1 Western European, Latin-1.
ISO-8859-5ISO8859-5 Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8  ASCII compatible multi-byte 8-bit Unicode.
cp866ibm866, 866 DOS-specific Cyrillic charset.
cp1251Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset.
cp1252Windows-1252, 1252 Windows specific charset for Western European.
KOI8-Rkoi8-ru, koi8r Russian.
BIG5950 Traditional Chinese, mainly used in Taiwan.
GB2312936 Simplified Chinese, national standard character set.
BIG5-HKSCS  Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JISSJIS, SJIS-win, cp932, 932 Japanese
EUC-JPEUCJP, eucJP-win Japanese
MacRoman  Charset that was used by Mac OS.
''  An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.
View More Details (and 11 discussions about this topic) Here...

How to set infinite execution time in a PHP script

Add the following code to set unlimited execution time for a PHP script:

  1. set_time_limit(0)

You can also update max_execution_time in php.ini

If the value is 0, it is actually unlimited. Otherwise it is that number of seconds.

View More Details (and 5 discussions about this topic) Here...

How to sort an array of dates and times?

In PHP it is very easy to sort an array of dates and times. All you need to do is convert it to a (integer) timestamp, and then do a normal sort. Here are more details:

First, convert the dates into a timestamp

A timestamp is time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). The current timestamp (when this page was last cached, anyway) is: 1575590523 (time()).

Because there is no standard PHP array function for sorting date strings we will have to convert it ourselves. But we can make a closure, and pass that to usort(&$array, $compare_func) (which lets us define our own function to do the comparisons for the sorting)

The custom comparison function for usort takes 2 parameters. It returns either -1, 0, or 1 depending on how they compare (1 if $a is less than $b; -1 if $a is greater than $b; 0 if equal). We can use PHP's spaceship operator for this (<=>) .

Let's set up the data:

  1.     $dates = [
  2.  
  3.     "10 September 2000",
  4.     "10 September 2020",
  5.     "9 September 2020",
  6.     "9 September 2000",
  7.     "5 April 1999",
  8.     "20 April 1998",
  9. ];

And now the comparison function:

  1. $compare_function = function($a,$b) {
  2.  
  3.         $a_timestamp = strtotime($a); // convert a (string) date/time to a (int) timestamp
  4.         $b_timestamp = strtotime($b);
  5.  
  6.         // new feature in php 7
  7.         return $a_timestamp <=> $b_timestamp;
  8.  
  9.         /* old way to do it:
  10.  
  11.                 if ($a_timestamp > $b_timestamp) {
  12.                     return -1;
  13.                 }
  14.                 elseif ($a_timestamp < $b_timestamp) {
  15.                     return 1;
  16.                 }
  17.                 else {
  18.                     return 0;
  19.                 }
  20.  
  21.         */
  22.  
  23.                 };

Now we have everything we need - let's sort that data!

  1.         usort($dates, $compare_function);
  2.         var_dump($dates);
array:6 [
  0 => "20 April 1998"
  1 => "5 April 1999"
  2 => "9 September 2000"
  3 => "10 September 2000"
  4 => "9 September 2020"
  5 => "10 September 2020"
]
View More Details (and 11 discussions about this topic) Here...

How to use Anonymous classes in PHP 7?

PHP 7 introduced a new feature of Anonymous classes. Here is how to use them.

  1. // Pre PHP 7 code
  2. class Logger
  3. {
  4.     public function log($msg)
  5.     {
  6.         echo $msg;
  7.     }
  8. }
  9.  
  10. $util->setLogger(new Logger());
  11.  
  12. // PHP 7+ code
  13. $util->setLogger(new class {
  14.     public function log($msg)
  15.     {
  16.         echo $msg;
  17.     }
  18. });

They are great for mocking, as you can easily write quick classes to do their purposes for a test.

You cannot define an anonymous class without instantiating it at the same time. I.e. when you create an anonymous class, it is instantiated at the same time.

They can extend other classes and use interfaces too.

View More Details (and 12 discussions about this topic) Here...

How to view all installed PHP modules?

It is very simple to see all installed PHP modules. Just run the following command:

php -m

For example, the output on one of my VM machines is:

$ php -m
[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dba
dom
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
imap
json
ldap
libxml
mbstring
mcrypt
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
pdo_pgsql
pdo_sqlite
Phar
posix
Reflection
session
shmop
SimpleXML
soap
sockets
SPL
sqlite3
standard
sysvsem
sysvshm
tokenizer
wddx
xml
xmlreader
xmlrpc
xmlwriter
xsl
zip
zlib

[Zend Modules]
View More Details (and 5 discussions about this topic) Here...

Is multiple inheritance supported in PHP?

Nope! You can extend a class only once. You can, however, use traits.

View More Details (and 7 discussions about this topic) Here...

PHP Date commonly used formats

The date() function in PHP is very simple. It takes two arguments (the second is optional) - the $format, and the optional $timestamp - date('y-m-d',time()- 31536000) = 17-10-12

(If no timestamp is provided then it uses the current date/time. The timestamp is in seconds, since January 1 1970 00:00:00 GMT. Current timestamp right now: 1539357386

The most difficult part of using date() in PHP is remembering its format.

The following characters are recognized in the format parameter string
format characterDescriptionExample returned values
Day------
dDay of the month, 2 digits with leading zeros01 to 31
DA textual representation of a day, three lettersMon through Sun
jDay of the month without leading zeros1 to 31
l (lowercase 'L')A full textual representation of the day of the weekSunday through Saturday
NISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)1 (for Monday) through 7 (for Sunday)
SEnglish ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
wNumeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
zThe day of the year (starting from 0)0 through 365
Week------
WISO-8601 week number of year, weeks starting on MondayExample: 42 (the 42nd week in the year)
Month------
FA full textual representation of a month, such as January or MarchJanuary through December
mNumeric representation of a month, with leading zeros01 through 12
MA short textual representation of a month, three lettersJan through Dec
nNumeric representation of a month, without leading zeros1 through 12
tNumber of days in the given month28 through 31
Year------
LWhether it's a leap year1 if it is a leap year, 0 otherwise.
oISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)Examples: 1999 or 2003
YA full numeric representation of a year, 4 digitsExamples: 1999 or 2003
yA two digit representation of a yearExamples: 99 or 03
Time------
aLowercase Ante meridiem and Post meridiemam or pm
AUppercase Ante meridiem and Post meridiemAM or PM
BSwatch Internet time000 through 999
g12-hour format of an hour without leading zeros1 through 12
G24-hour format of an hour without leading zeros0 through 23
h12-hour format of an hour with leading zeros01 through 12
H24-hour format of an hour with leading zeros00 through 23
iMinutes with leading zeros00 to 59
sSeconds, with leading zeros00 through 59
u Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.Example: 654321
v Milliseconds (added in PHP 7.0.0). Same note applies as for u.Example: 654
Timezone------
eTimezone identifier (added in PHP 5.1.0)Examples: UTC, GMT, Atlantic/Azores
I (capital i)Whether or not the date is in daylight saving time1 if Daylight Saving Time, 0 otherwise.
ODifference to Greenwich time (GMT) in hoursExample: +0200
PDifference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)Example: +02:00
TTimezone abbreviationExamples: EST, MDT ...
ZTimezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.-43200 through 50400
Full Date/Time------
cISO 8601 date (added in PHP 5)2004-02-12T15:19:21+00:00
r» RFC 2822 formatted dateExample: Thu, 21 Dec 2000 16:01:07 +0200
USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT)See also time()
View More Details (and 5 discussions about this topic) Here...

What are generators in PHP, and how do they compare to arrays?

Generators are like little functions that let you iterate over it (for example with a foreach) and it will 'yield' a value on every iteration.

If you do foreach(range(1,10000000) as $i) {...} then PHP will probably crash, as it has to first 'create' the array (with items from 1 to 10000000 in it). This isn't terribly memory efficient.

A better way to do it is using a generator. It will 'output' (yield) one value at a time, so uses much less memory.

Here is an example of a generator - take note of the yield line.

  1. function range_generator($from, $to) {
  2.     for ($i = $from; $i <= $to; $i++) {
  3.         yield $i; // here!
  4.     }
  5. }

The yield $i is sort of the same as return $i, however the code that called range_generator() (i.e. the foreach loop) can keep asking it to yield again and again and again...

This range_generator() function is often called xrange() in other languages that have this function built in, BTW

The function above can be used like this:

  1. foreach(range_generator(1,10000000) as $i) {
  2.         echo $i;
  3.  
  4.         }
  1. The foreach loop starts, and gives the generator two parameters, 1 and 10000000.
  2. The generator 'beings', and starts its own for loop. In its first iteration, it will yield 1.
  3. This is then passed back to the foreach ( as $i), and the code within the foreach loop is executed (echo $i).
  4. Once the first iteration of the foreach is complete, it will go back to the range generator, which will then finish its for loop (nothing else for it to do), and go into its own second iteration of that loop, until it reaches the yield $i again, where the pattern repeats.
  5. This carries on until the range_generator stops yielding a variables back to the foreach loop.

If you used the standard range(1,10000000) function then the array of 10000000 elements has to be created and stay in memory. Using this generator means that only one $i exists at a time, massively reducing memory load. If I use the standard range(1,10000000) function, I get a Allowed memory size of 134217728 bytes exhausted (tried to allocate 536870920 bytes) exception.

The memory usage with a generators is constant, no matter how many times it iterates. It isn't really even fair to compare an array and a generator, as they aren't really the same thing. But you can loop them in things like a foreach loop.

How to send data to the generator

When you work with generators, you are actually working with the Generator class. There are a number of methods available to you:

  • public mixed current() - Get the yielded value
  • public mixed getReturn() - Get the return value of a generator. This is used after you have finished using the generator - as soon as you return anything (null, a value) the generator will stop yielding
  • public mixed key() - Get the yielded key
  • public void next() - Resume execution of the generator (same as calling Generator::send() with NULL as argument)
  • public void rewind() - Rewind the iterator. N.B. If iteration has already begun, this will throw an exception.
  • public mixed send( $value ) - Sends the given value to the generator as the result of the current yield expression and resumes execution of the generator.(see below for more details)
  • public mixed throw( Throwable $exception ) -- Throw an exception into the generator, and then resumes execution of the generator. The behavior will be the same as if the current yield expression was replaced with a throw $exception statement
  • public bool valid() - Check if the iterator has been closed
  • public void __wakeup() - not really used - it will just throw an exception as you cannot serialise generators.

I think the most important one to know is the send($val) method. Here is an example:

  1. <?php
  2. function printer() {
  3.     echo "I'm printer!".PHP_EOL;
  4.     while (true) {
  5.         $string = yield;
  6.         echo $string.PHP_EOL;
  7.     }
  8. }
  9.  
  10. $printer = printer();
  11. $printer->send('Hello world!');
  12. $printer->send('Bye world!');
  13. ?>

This will output the following:

I'm printer!
Hello world!
Bye world!

When to use generators and their yielding feature

If you are ever doing something with a large amount of data and iterating over all of it, then your first thought should always be if you should be using a generator.

You don't want to be storing huge amounts of data in memory, especially if you are actually only working on one part (one line, one element, one document, one row) at a time.

Good times to use generators:

  • Dealing with things like database rows. It is fine to process a few hundred (even a few thousand) in a normal array based loop. But if you have a big data set then you will very quickly run out of memory. Put it in a generator and handle one row at a time.
  • When working with log files. Log files can easily be many GBs of text. Loading it all into memory at once, again, would be a bad idea. But cycling through it line by line means you won't face any memory issues.
View More Details (and 12 discussions about this topic) Here...

What are PHP's PSRs?

PSRs are PHP Standards Recommendations. They are a standard and clearly defined way to do many common tasks.

Some common PSRs:

PSR-0 - Autoloading Standard
This is not in use any more - you should use PSR-4.

It describes the mandatory requirements that must be adhered to for autoloader interoperability.

PSR-1 - Basic Coding Standard

It comprises what should be considered the standard coding elements that are required to ensure a high level of technical interoperability between shared PHP code.

PSR-2 - Coding Style Guide

It considers PSR-1 and it is intended to reduce cognitive friction when scanning code from different authors. It does so by enumerating a shared set of rules and expectations about how to format PHP code.

Some of the basic and main rules:

  • Use spaces, not tabs (4 spaces = 1 tab)
  • The namespace ... should be on its own line
  • The closing ?> must not be present, for files containing only PHP
  • PHP keywords (true, false, null) must always be in lower case
  • The extends and implements must be on the same line as the class name
  • The opening bracket must go on its own (new) line
  • You must always provide a public/protected/private for all object properties. Same for methods.
  • There must be exactly one space after the comma between method or function parameters, and no space before the comma
  • Function and method parameters may be spread over several lines, if you wish
  • And if structures must look like the following:
  1. <?php
  2. if ($expr1) {
  3.     // if body
  4. } elseif ($expr2) {
  5.     // elseif body
  6. } else {
  7.     // else body;
  8. }

You can find the full specs here.

PSR-3 - Logger Interface

It describes a common interface for logging libraries.

PSR-4 - Autoloading Standard

It describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be auto loaded according to the specification.

PSR-4 is often used with Composer's composer.json to help with autoloading of PHP classes.

PSR-5 - PHPDoc Standard
This spec is only a draft (as of Oct 2018)

The main purpose of this PSR is to provide a complete and formal definition of the PHPDoc standard. This PSR deviates from its predecessor, the de facto PHPDoc Standard associated with phpDocumentor 1.x, to provide support for newer features in the PHP language and to address some of the shortcomings of its predecessor. Is only a draft (as of Oct 2018)

PSR-6 - Caching Interface

The goal of this PSR is to allow developers to create cache-aware libraries that can be integrated into existing frameworks and systems without the need for custom development.

Here are the interfaces - I've removed most of the comments to make this page more readable, but if you want to see full details then please go here.

CacheItemInterface

CacheItemInterface defines an item inside a cache system.

  1. <?php
  2.  
  3. namespace Psr\Cache;
  4.  
  5. // CacheItemInterface defines an interface for interacting with objects inside a cache.
  6. interface CacheItemInterface
  7. {
  8.      // Returns the key for the current cache item.
  9.     public function getKey();
  10.  
  11.      // Retrieves the value of the item from the cache associated with this object's key.
  12.     public function get();
  13.  
  14.      // Confirms if the cache item lookup resulted in a cache hit.
  15.     public function isHit();
  16.  
  17.      // Sets the value represented by this cache item.
  18.     public function set($value);
  19.  
  20.      // Sets the expiration time for this cache item.
  21.     public function expiresAt($expiration);
  22.  
  23.      // Sets the expiration time for this cache item.
  24.     public function expiresAfter($time);
  25.  
  26. }
CacheItemPoolInterface

The primary purpose of Cache\CacheItemPoolInterface is to accept a key from the Calling Library and return the associated Cache\CacheItemInterface object.

  1. <?php
  2.  
  3. namespace Psr\Cache;
  4.  
  5. // CacheItemPoolInterface generates CacheItemInterface objects.
  6. interface CacheItemPoolInterface
  7. {
  8.      // Returns a Cache Item representing the specified key.
  9.     public function getItem($key);
  10.  
  11.      // Returns a traversable set of cache items.
  12.     public function getItems(array $keys = array());
  13.  
  14.      // Confirms if the cache contains specified cache item.
  15.     public function hasItem($key);
  16.  
  17.      // Deletes all items in the pool.
  18.     public function clear();
  19.  
  20.      // Removes the item from the pool.
  21.     public function deleteItem($key);
  22.  
  23.      // Removes multiple items from the pool.
  24.     public function deleteItems(array $keys);
  25.  
  26.      // Persists a cache item immediately.
  27.     public function save(CacheItemInterface $item);
  28.  
  29.      // Sets a cache item to be persisted later.
  30.     public function saveDeferred(CacheItemInterface $item);
  31.  
  32.      // Persists any deferred cache items.
  33.     public function commit();
  34. }
CacheException and InvalidArgumentException

There are two interfaces for exceptions related to PSR-6 that should be used.

CacheException: Exception interface for all exceptions thrown by an Implementing Library

InvalidArgumentException: Exception interface for invalid cache arguments.

PSR-7 explained: HTTP Message Interface

What is PSR-7, and when to use it? PSR 7 is a set of interfaces for HTTP messages and URIs, used when PHP is used as a web server (i.e. over HTTP).

If you want to get an instance of a PSR-7 request in Laravel, then you must use the symfony/psr-http-message-bridge and zendframework/zend-diactoros package. Then you can get a Psr\Http\Message\ServerRequestInterface class automatically injected into your controller methods by type hinting the ServerRequestInterface interface as a method param.

PSR 7 basically describes common interfaces for representing HTTP messages as described in RFC 7230 and RFC 7231, and URIs for use with HTTP messages as described in RFC 3986.

A common package used is the Zend Diactoros one (which is also the one recommended to use if you want to use PSR-7 requests with Laravel. Find more details here.

PSR-9 - Security Disclosure
This spec is only a draft (as of Oct 2018)

It gives project leads a clearly dIt gives project leads a clearly defined approach to enabling end users to discover security disclosures using a clearly defined structured format for these disclosures. Is only a draft (as of Oct 2018)

PSR-10 - Security Advisories
This spec is only a draft (as of Oct 2018)

It gives researchers, project leads, upstream project leadIt gives researchers, project leads, upstream project leads and end users a defined and structured process for disclosing security vulnerabilities. Is only a draft (as of Oct 2018)

PSR-11 - Container Interface
This spec is only a draft (as of Oct 2018)

It describes a common interface for dependency injection containers. The goal is to standardize how frameworks and libraries make use of a container to obtain objects and parameters (called entries in the rest of this document). Is only a draft (as of Oct 2018)

PSR-12 - Extended Coding Style Guide
This spec is only a draft (as of Oct 2018)

It extends, expands and replaces PSR-2, the coding style guide and requires adherence to PSR-1, the basic coding standard. Is only a draft (as of Oct 2018)

Source: Wikipedia's list of all PSRs

View More Details (and 3 discussions about this topic) Here...

What are the main error types in PHP

There are 3 main types of errors: Notices (not very important), Warnings (quite important), and Fatal (so important that the script will halt).

(Please don't ignore Notices just because I said they're not important. It was only to give a comparison between those three. There is often very important information in the Notice errors)

Notices (E_USER_NOTICE) - These are non-critical errors that do not stop further execution of the script (by default). If you try to use a variable that has not been set, you will get an E_USER_NOTICE notice error, but the script will (in default PHP settings) continue to run.

Warnings (E_USER_WARNING) - These are similar to notices, but more important. The script will still run (with default PHP settings), however, you should really pay attention to them. A warning error would be shown (/logged) for things such as attempting to use include() on a file that does not exist.

Fatal Errors (E_ERROR, or E_CORE_ERROR if PHP cannot initialise) - if your scripts encounter a fatal error, it will stop execution. A fatal error comes from doing things such as calling a function that does not exist, or calling require() for a file that does not exist.

View More Details (and 9 discussions about this topic) Here...

What are the predefined variables in PHP?

There are a handful of predefined variables in PHP. They include:

$GLOBALS — References all variables available in global scope

$_SERVER — Server and execution environment information

$_GET — HTTP GET variables

$_POST — HTTP POST variables

$_FILES — HTTP File Upload variables

$_REQUEST — HTTP Request variables

$_SESSION — Session variables

$_ENV — Environment variables

$_COOKIE — HTTP Cookies

$php_errormsg — The previous error message

$HTTP_RAW_POST_DATA — Raw POST data

$http_response_header — HTTP response headers

$argc — The number of arguments passed to script

$argv — Array of arguments passed to script

The most commonly used ones, in my opinion, are $_GET, $_POST, $_SERVER, $_FILES, $_SESSION and $_COOKIE (so, the majority of them!)

View More Details (and 7 discussions about this topic) Here...

What are the SPL data structures

The SPL (Standard PHP Library) includes several data structures that you should be aware of and hopefully use. Here is an overview of them:

SplDoublyLinkedList — The SplDoublyLinkedList class - this provides the main functionalities of a doubly linked list

SplStack — The SplStack class - this provides the main functionalities of a stack implemented using a doubly linked list.

SplQueue — The SplQueue class - this provides the main functionalities of a queue implemented using a doubly linked list.

SplHeap — The SplHeap class - this provides the main functionalities of a Heap.

SplMaxHeap — The SplMaxHeap class - this provides the main functionalities of a heap, keeping the maximum on the top.

SplMinHeap — The SplMinHeap class - this provides the main functionalities of a heap, keeping the minimum on the top.

SplPriorityQueue — The SplPriorityQueue class - this provides the main functionalities of a prioritized queue, implemented using a max heap.

SplFixedArray — The SplFixedArray class - this provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation.

SplObjectStorage — The SplObjectStorage class - this provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.

View More Details (and 12 discussions about this topic) Here...

What are the SPL Iterators in PHP?

The iterators in the Standard PHP Library (SPL) are the following:

AppendIterator — The AppendIterator class

ArrayIterator — The ArrayIterator class

CachingIterator — The CachingIterator class

CallbackFilterIterator — The CallbackFilterIterator class

DirectoryIterator — The DirectoryIterator class

EmptyIterator — The EmptyIterator class

FilesystemIterator — The FilesystemIterator class

FilterIterator — The FilterIterator class

GlobIterator — The GlobIterator class

InfiniteIterator — The InfiniteIterator class

IteratorIterator — The IteratorIterator class

LimitIterator — The LimitIterator class

MultipleIterator — The MultipleIterator class

NoRewindIterator — The NoRewindIterator class

ParentIterator — The ParentIterator class

RecursiveArrayIterator — The RecursiveArrayIterator class

RecursiveCachingIterator — The RecursiveCachingIterator class

RecursiveCallbackFilterIterator — The RecursiveCallbackFilterIterator class

RecursiveDirectoryIterator — The RecursiveDirectoryIterator class

RecursiveFilterIterator — The RecursiveFilterIterator class

RecursiveIteratorIterator — The RecursiveIteratorIterator class

RecursiveRegexIterator — The RecursiveRegexIterator class

RecursiveTreeIterator — The RecursiveTreeIterator class

RegexIterator — The RegexIterator class

View More Details (and 3 discussions about this topic) Here...

What does 'final class' and 'final function' (final method) mean in PHP?

If a class is defined as final class then no other class can extend it. I.e. the following would result in an error:

  1.         final class DontExtendMe {}
  2.         class ThisCausesAnError extends DontExtendMe {}

A final method (final function ...) means that any subclasses of it's class cannot be overridden.

View More Details (and 9 discussions about this topic) Here...

What does PEAR stand for?

PEAR stands for 'PHP Extension and Application Repository'

It is a set of packages that provide further functionality than what is just built into plain PHP. It used to be more popular, I would say now that PEAR is quite dead. If you need to install a package, it will normally be a standard package installed with Composer. I remember years ago (10 years ago?) it was common to be working with PEAR packages. In 2018, not so much...

View More Details (and 12 discussions about this topic) Here...

What is camel case?

Camel case is where you write words/phrases so that each word begins with a capital letter (but lower case for the rest of the word), and there is no space (or other punctuation) between words. It is often used for function/method names, or variables. For example showBlogPosts().

(Note: often the first character will be lower case for things like method names and parameters. The first character will often be upper case for class names (e.g. class BlogController {...}.

Other alternatives include kebab-case (all lowercase, separated by a hyphen -). Also known as lisp-case or spinal-case.

There is also Train-Case (lowercase, but first letter uppercase, separated by hyphens).

View More Details (and 5 discussions about this topic) Here...

What is snake case?

Snake case is the way of writing words/phrases, where each word is separated by an underscore character. It is often used for variable names. For example $blog_posts is in snake case. Sometimes it is written as snake_case.

See also Camel case (e.g. $camelCaseVariable)

View More Details (and 7 discussions about this topic) Here...

What is the difference between empty(), isset(), != null, is_null() in PHP

All four of these are ways to basically check if a variable (or return value) is empty or null. But they all have slight differences in how they approach it.

A lot of people assume that empty() and isset() are opposites, but if you look at the table at the bottom of this page you will see they aren't quite opposite. (e.g. an empty array ([]) will return true for both empty([]) and isset([]) They both also return true for values such as "0", 0, 0.0.

empty($var)

This will check if the variable is empty. The official docs list it as "A variable is considered empty if it does not exist or if its value equals FALSE.".

This means that empty() will return true if:

  1. if $var does not exist
  2. if $var = false
  3. if $var = null
  4. if $var = [] (empty array)
  5. if $var = "" (empty string)
  6. if $var = 0
  7. if $var = "0" (0 as a string)
  8. if $var = 0.0 (0 as a float)

isset($val)

isset() is a mix between checking if something is set (i.e. the variable exists, or in the case of arrays if the array key exists)) and checking if it is not null

It will return true for most situations, unless the variable does not exist, or if the variable = null

If you supply multiple arguments, it will only return true if all are set.

  1. $a  = $b = $c = true;
  2. $null1 = $null2 = null;
  3.  
  4. var_dump( [
  5.     "a_b_c" => isset($a,$b,$c),
  6.     "null1_null2" => isset($null1,$null2),
  7.     "a_b_null1" => isset($a,$b,$null1),
  8. ]);
array(3) {
    ["a b c"]=> bool(true) // all were set and have values
    ["null1 null2"]=> bool(false) // both were null
    ["a b null1"]=> bool(false) // one was null
}

$val == null

This will return true for all situations where $val has a value. There are some weird situations that you must be aware of though.

It will return false for $val = "0"; var_dump($val == null); . I don't know why.

$val === null and is_null($val)

The only time that either of these statements will return true is if $val actually is null (i.e. $val=null;).

Testempty($val)isset($val)$val == null$val === nullis_null($val)
false true true true false false
true false true false false false
null true false true true true
empty array true true true false false
array with 1 item false true false false false
empty string ("") true true true false false
space (" ") false true false false false
0 true true true false false
"0" (as string) true true false false false
0.0 (as float) true true true false false
View More Details (and 8 discussions about this topic) Here...

What is the max size, by default, of GET variables?

By default the max size for values in the $_GET[] array is 2048 bytes. The $_POST[] has no such limit.

View More Details (and 8 discussions about this topic) Here...

What is the null coalescing operator in PHP7?

The null coalescing operator is two question marks: ??. It is used to replace some ternary operations. Here is an example:

  1. // old way
  2. $var = isset($_GET['variable']) ? $_GET['variable'] : "default_val";
  3.  
  4. // new way - null coalescing:
  5. $var = $_GET["variable"] ?? "default_val";

Both of the above lines do the same thing: they set $var to $_GET['variable'] if it is set (if it passes isset()), but if not then it sets $var to 'default_val'.

View More Details (and 6 discussions about this topic) Here...

What is the spaceship operator (<=>) in PHP?

The spaceship operator was a new feature in PHP 7. It looks like this: <==>

It will return 0 if both sides are equal. 1 if left is greater. -1 if right is greater.

  1.     var_dump( [
  2.  
  3.         "1 <=> 1" => 1 <=> 1,
  4.         "1 <=> 0" => 1 <=> 0,
  5.         "0 <=> 1" => 0 <=> 1,
  6.         "1 <=> \"1\"" => 1 <=> "1",
  7.         "\"abc\" <=> \"abc\"" => "abc" <=> "abc",
  8.         "\"zzz\" <=> \"abc\"" => "zzz" <=> "abc",
  9.  
  10.         ]);
array(6) {
  ["1 <=> 1"]=> 0
  ["1 <=> 0"]=> 1
  ["0 <=> 1"]=> -1
  ["1 <=> "1""]=> 0
  [""abc" <=> "abc""]=> 0
  [""zzz" <=> "abc""]=> 1
}
View More Details (and 5 discussions about this topic) Here...

When is __destruct called in PHP?

The __destruct method is called either during the shutdown sequence (i.e. end of execution of a script), or when there are no references to an object.

Remember that if you put a __destruct() method in a subclass, you must call parent::__destruct() if you want the parent's destruct method to execute (assuming there is one).

The method will be called even if exit() is called. However, if exit() is called from within a destructor, then no further destructors will be called.

Note: completely unrelated to Array Destructuring.

View More Details (and 5 discussions about this topic) Here...