12. Array Functions
12. Array Functions
count() Function
• The count() function returns the number of
elements in an array.
– Syntax
• count(array,mode);
Count() Parameters
Parameter Description
array Required. Specifies the array
mode •Optional. Specifies the mode. Possible values:0 - Default. Does not
count all elements of multidimensional arrays
•1 - Counts the array recursively (counts all the elements of
multidimensional arrays)
Normal Count() Example
• <?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Recursive Count() Example
• <?php
$cars=array("Volvo"=>array("XC60","XC90"),
"BMW"=>array("X3","X5"),
"Toyota"=>array("Highlander"));
if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
current() Function
• The current() function returns the value of the
current element in an array.
• Every array has an internal pointer to its
"current" element, which is initialized to the
first element inserted into the array.
Tip: This function does not move the arrays
internal pointer.
Current() Example
• <?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");
Parameter Description
array Required. Specifies the array to sort
sortingtype •Optional. Specifies how to compare the array elements/items. Possible
values:0 = SORT_REGULAR - Default. Compare items normally (don't
change types)
•1 = SORT_NUMERIC - Compare items numerically
•2 = SORT_STRING - Compare items as strings
Sort() Example
• <?php
$numbers=array(4,6,2,22,11);
sort($numbers);
foreach ($numbers as $i)
{
echo $i." ";
}
?>
rsort() Function
• The rsort() function sorts an indexed array in
descending order.
– Syntax
• rsort(array,sortingtype);
Rsort() Example
• <?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
asort() Function
• The asort() function sorts an associative array
in ascending order, according to the value.
– Syntax
• asort(array,sortingtype);
asort() Example
• <?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=
>"43");
asort($age);
?>
arsort() Function
• The arsort() function sorts an associative array
in descending order, according to the value.
– Syntax
• arsort(array,sortingtype);
arsort() Example
• <?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=
>"43");
arsort($age);
?>
array_merge() Function
• The array_merge() function merges one or
more arrays into one array.
– Syntax
• array_merge(array1,array2,array3...)
array_merge() example
• <!DOCTYPE html>
<html>
<body>
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
</body>
</html>
• Output :
– Array ( [0] => red [1] => green [2] => blue [3] => yellow )
array_reverse() Function
• The array_reverse() function returns an array
in the reverse order.
– Syntax
• array_reverse(array)
array_reverse() Function
• <!DOCTYPE html>
<html>
<body>
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyot
a");
print_r(array_reverse($a));
?>
</body>
</html>
Output:
Array ( [c] => Toyota [b] => BMW [a] => Volvo )