PHP Array Functions
PHP Provides wide range of functions to perform operations on array.
is Array Function Example
During Runtime if you want to check with a variable is a variable or an array then php is_array() function help out from this trouble.
<?php
//Getting the Length of an Array
$fruit[]="Apple";
$fruit[]="Orange";
$fruit[]="Mango";
echo is_array($fruit)?"It's an array":"it's a variable";
?>
Array Length Function Example
In Programming tasks many time we require to know the length of an unknown array.
<?php
//Getting the Length of an Array
$fruit[]="Apple";
$fruit[]="Orange";
$fruit[]="Mango";
echo count($fruit);
?>
Print an Array Example
PHP provide print_r() function to print whole array with single line.
<?php
$colors=array("white","green","black");
print_r($colors);
?>
Array Sort Function Example
Sorting is very important task during retrieval/display the data from database. PHP Provides different sort functions, but currently we will discuss sort() & rsort() functions.
<?php
$colors=array("white","green","black");
sort($colors); //Sort an array in ascending order
print_r($colors);
$rcolors=array("black","white","green");
rsort($rcolors); //Sort an array in reverse order
print_r($rcolors);
?>
Array Shuffle Function Example
There are many times when you need to put an array an random order. so don’t worry PHP Have shuffle() function to perform this operation.
<?php
//Shuffle
$colors=array("red","green","yellow","blue");
shuffle($colors);
print_r($colors); // every time you will see the different color at different index
?>
Array Reset Function Example
Reset() function moves the array index pointer to the first index of an array.
<?php
//Reset
$colors=array("red","green","yellow","blue");
echo reset($colors);
?>
Array End Function Example
End() function moves the array index pointer to the last index of an array.
<?php
$colors=array("red","green","yellow","blue");
echo end($colors); //Move the array Index Pointer to Last Index of an array and return the value of last index
?>
Explode Function Example
Some time we have long string with same pattern and want to divide this long string into array. explode() function will convert a string to an array.
<?php
//Explode
$URL="phpdocs.com/php/variables";
$URL_array=explode('/',$URL); //divide the string into different parts on the base of forward slash (/)
print_r($URL_array);
}
?>