Array Functions in PHP: PART 1

Introduction

The array type in PHP is an ordered map of
elements of the same type that associates values to keys, or you can say that the array type is very similar to the string type, which, for that reason, is often referred to as an array of characters. Here I am going to explain some of the PHP array functions.

PHP array Function

The array() function creates an array. The array function has two parameters (key and values). If you not specify a key value, an integer key is automatically generated, starting at 0 and increasing by one for each value.

Syntax

array (key =>value)

Parameter in array function

It takes two parameters; they are:

Parameter Description
key It is optional parameter that specifies the key , of type numeric or string.
value It specifies the value.

Example of array function

The following is an example of an array function:

<?php

$fruits=array("Apple","Banana","Raspberry","Apricot");

echo "<pre>";

print_r($fruits);

?>

Output

array-function-in-php.jpg

PHP array_change_key_case Function

The array_change_key_case() function returns an array with all keys from the input converted to either all lowercase or all uppercase.

Syntax

array (input , case)

Parameter in array_change_key_case function

It takes two parameters; they are:

Parameter Description
input It specifies an array to work on.
case It is optional parameter and it's possible values are:
  • CASE_LOWER - Returns the array key value in lower case.
  • CASE_UPPER - Returns the array key value in upper case.


Example of array_change_key_case function

The following is an example of the array_change_key_case function:

<?php

echo"<h1>Upper Case</h1>";

$input_array=array("First" => "Cat", "Second" => "Rat");

echo "<pre>";

print_r(array_change_key_case($input_array, CASE_UPPER));

echo "<h1>Lower Case</h1>";

$input_array = array("First" => "Cat", "Second" => "Rat");

echo "<pre>";

print_r(array_change_key_case($input_array, CASE_LOWER));

?>

Output

array-change-key-case-function-in-php.jpg 

PHP array_chunk Function

The array_chunk function splits an array into chunks of new arrays.

Syntax

array_chunk (array , size, preserve_keys)

Parameter in array_chunk function

It takes three parameters; they are:

Parameter Description
array It specifies array to use.
size It specifies the size of each chunk.
preserve_keys It is optional parameter and it's possible values are:
  • True - Set to true keys will be preserved.
  • False- Default. Does not preserve the key from the original array.

Example of array_chunk function

The following is an example of the array_chunk function:

<?php

$input_array=array('Sharad', 'Arun', 'Mohit', 'Satya', 'Vishal');

echo "<pre>";

print_r(array_chunk($input_array, 3));

echo "<pre>";

print_r(array_chunk($input_array, 3, true));

?>

Output

array-chunk-function-in-php.jpg


Similar Articles