PHP array functions to understand

  • is_array(): check if the variable is array or not.
if( is_array( $arrayVar ) ){
    // code to work with array data 
} else {
    throw new Exception('data passed is not array!');
}
$string = 'WordPress Developer';
$words = explode( ' ', $string );
var_dump( $words );
// output:
Array
(
    [0] => WordPress
    [1] => Developer
)
  • implode(): creates a string from array values.
$arr = [ 'WordPress', 'Developer' ];
$words = implode( ' ', $arr );
var_dump( $words );
// output:
string(19) "WordPress Developer"
  • unset(): destroy a variable or an array value specified by key/index.
unset( $var ); // destroy a single variable
unset( $var1, $var2 ); // destroy multiple variables
unset( $arrayVar['keyName'] ); // destroy array element (key)
unset( $arrayVar[2] ); // destroy array element (index)
  • array_chunk(): split an array into smaller sized arrays (aka chunks).
$large_array = [ 'a', 'b', 'c', 'd', 'e' ];
print_r( array_chunk( $large_array, 2 ) );
// output:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

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

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

)
$alphabets = [ 'a', 'b', 'c', 'd', 'e' ];
print_r( array_slice( $alphabets, 2 ) ); // here 2 is offset (or starting position)!
// output:
Array
(
    [0] => c
    [1] => d
    [2] => e
)
Note: arguments: $array, $offset, $preserve_key
Understand these arguments well before using it.
  • in_array(): checks if a value exists in an array or not. It is case-sensitive.
$color = [ 'red', 'Green', 'yellow' ];
if( in_array( 'red', $color ){
    echo 'Color: red'; // it will display
}
if( in_array( 'green', $color ) ) {
   echo 'Color: green'; // it will not display
}
  • array_search(): checks if a value exists and returns the first corresponding key if exists.
$color_index = [ 'color1' => 'blue', 'color2' => 'red', 'color3' => 'green', 'color4' => 'blue' ];

$index1 = array_search( 'green', $color_index );
echo '<br>' . $index1 . '<br>'; // color3

$index2 = array_search( 'blue', $color_index );
echo $index2. '<br>'; // color1 (because its first found)

Here is a complete list of built-in functions for working with PHP arrays (PHP Array Functions).

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.