26 Aug 09 PHP Programming Tutorial: Array Functions



Now that we have a basic understanding of arrays from our last PHP Arrays tutorial, it’s time to find out some more things we can do with them using Array Functions.

If you have an array full of numbers, you can use some array functions to count and find values:

<?php $numArray = array(28,9,3,44,72); // create an array ?>
Minimum Value: <?php echo min($numArray); // What is the minimum number in our array? ?><br />
Maximum Value: <?php echo max($numArray); // What is the maximum number in our array? ?><br />
Count: <?php echo count($numArray); // How many items are in our array? ?>

As expected, PHP gives us the information we wanted.

Let’s say we want to better sort our array of mixed numbers. PHP has array functions for this too:

<?php $numArray = array(28,9,3,44,72); // create an array ?>
Sort: <?php sort($numArray); // Sort our array from max to min.?><br />
 
<?php print_r($numArray); // Output this array to our web browser. ?><br />
 
Reverse Sort: <?php echo rsort($numArray); // Sort our array from min to max. ?><br />
 
<?php print_r($numArray); // Output this array to our web browser. ?>

Here are some other popular array functions:

<?php
$x = array(1,2);
$y = array(3,4);
 
print_r(array_merge($x,$y)); // the array_merge() function combines multiple arrays into one.
?>
<?php
$array = array("John", "Billy", "Joseph", "Melissa");
 
shuffle($array); // Shuffles the order of an array.
print_r($array);
?>
<?php
$array = array("1","1","2","3","4","4","5");
 
array_unique($array); // This removes duplicate values from an array. The extra 1 and 4 will be removed.
print_r($array);
?>

A full list of PHP’s array functions can be found at the official PHP web site here: http://us.php.net/manual/en/ref.array.php

Go back to Building PHP Scripts.

Leave a Comment