PHP Array Functions

You’ve already seen the list and each function, but PHP comes with numerous other functions for handling arrays. However, some of these functions are so fundamental that it’s worth taking the time to look at them here.

1. is_array

Arrays and variables share the same namespace. This means that you cannot have a
string variable called $fred and an array also called $fred. If you’re in doubt and your
code needs to check whether a variable is an array, you can use the is_array function
like this:

$fred = array("Volvo", "BMW", "Toyota");
echo (is_array($fred)) ? "Is an array" : "Is not an array";

Note that if $fred has not yet been assigned a value, an Undefined variable message
will be generated.


2. count

Although the each function and foreach … as loop structure are excellent ways to walk through an array’s contents, sometimes you need to know exactly how many elements there are in your array, particularly if you will be referencing them directly. To count all the elements in the top level of an array, use a command such as the following:

$fred = array("Volvo", "BMW", "Toyota");
echo count($fred);

Should you wish to know how many elements there are altogether in a multidimensional array, you can use a statement such as:

$fred = array("Volvo", "BMW", "Toyota", array(1,2,3,4) );
echo count($fred, 1);

The second parameter is optional and sets the mode to use. It should be either a 0 to limit counting to only the top level, or 1 to force recursive counting of all subarray elements too.


3. sort

Sorting is so common that PHP provides a built-in function. In its simplest form, you would use it like this:

$fred = array("Volvo", "BMW", "Toyota");

Unlike some other functions, the sort will act directly on the supplied array rather than returning a new array of sorted elements. Instead, it returns TRUE on success and FALSE on the error and also supports a few flags, but the main two that you might wish to use force sorting to be made either numerically or as strings, like this:

$fred = array("Volvo", "BMW", "Toyota",2,54,4);
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);

You can also sort an array in reverse order using the rsort function, like this:

$fred = array("Volvo", "BMW", "Toyota",2,54,4);
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);

4. shuffle

There may be times when you need the elements of an array to be put in random order, such as when you’re creating a game of playing cards:

$card =[1,2,3,4,5,6,11,9,7,8,10,12,13];

Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE on error.

5. explode

This is a very useful function with which you can take a string containing several items separated by a single character (or string of characters) and then place each of these items into an array. One handy example is to split up a sentence into an array containing all its words, as in Example 6-12.

Example 6-12. Exploding a string into an array using spaces

$temp = explode(' ', "This is a sentence with seven words");

This example prints out the following (on a single line when viewed in a browser):

 [0] => This
 [1] => is
 [2] => a
 [3] => sentence
 [4] => with
 [5] => seven
 [6] => words

The first parameter, the delimiter, need not be a space or even a single character. Example 6-13 shows a slight variation.
Example 6-13. Exploding a string delimited with *** into an array

$temp = explode('***', "A***sentence***with***asterisks");

The code in Example 6-13 prints out the following:

 [0] => A
 [1] => sentence
 [2] => with
 [3] => asterisks

6. extract

Sometimes it can be convenient to turn the key/value pairs from an array into PHP variables. One such time might be when you are processing the $_GET or $_POST variables assent to a PHP script by a form.
When a form is submitted over the Web, the web server unpacks the variables into a global array for the PHP script. If the variables were sent using the GET method, they will be placed in an associative array called $_GET; if they were sent using POST, they will be placed in an associative array called $_POST. You could, of course, walk through such associative arrays in the manner shown in the examples so far. However, sometimes you just want to store the values sent into variables for later use. In this case, you can have PHP do the job automatically for you:


So, for example, if the query string parameter q is sent to a PHP script along with the associated value Hi there, a new variable called $q will be created and assigned that value. Be careful with this approach, though, because if any extracted variables conflict with ones that you have already defined, your existing values will be overwritten. To avoid this possibility, you can use one of the many additional parameters available to this function, like this:

extract($_GET, EXTR_PREFIX_ALL, 'fromget');

In this case, all the new variables will begin with the given prefix string followed by an underscore, so $q will become $fromget_q. I strongly recommend that you use this version of the function when handling the $_GET and $_POST arrays, or any other array whose keys could be controlled by the user because malicious users could submit keys chosen deliberately to overwrite commonly used variable names and compromise your website.


7. compact

There are also times when you want to use compact, the inverse of extract, to create an array from variables and their values. Example 6-14 shows how you might use this function.

Example 6-14. Using the compact function

$fname = "Doctor";
$sname = "Who";
$planet = "Gallifrey";
$system = "Gridlock";
$constellation = "Kasterborous";
$contact = compact('fname', 'sname', 'planet', 'system', 'constellation');

The result of running Example 6-14 is:

[fname] => Doctor
[sname] => Who
[planet] => Gallifrey
[system] => Gridlock
[constellation] => Kasterborous

Note how compact requires the variable names to be supplied in quotes, not preceded
by a $ symbol. This is because the compact is looking for a list of variable names.
Another use of this function is for debugging when you wish to quickly view several
variables and their values, as in Example 6-15.

Example 6-15. Using compact to help with debugging

$j = 23;
$temp = "Hello";
$address = "1 Old Street";
$age = 61;
print_r(compact(explode(' ', 'j temp address age')));


This works by using the explode function to extract all the words from the string into an array, which is then passed to the compact function, which in turn returns an array to print_r, which finally shows its contents. If you copy and paste the print_r line of code, you only need to alter the variables named there for a quick printout of a group of variables’ values. In this example, the output is:

[j] => 23
[temp] => Hello
[address] => 1 Old Street
[age] => 61

8. reset

When the foreach … as a construct or the each function walks through an array, it keeps an internal PHP pointer that makes a note of which element of the array it should return next. If your code ever needs to return to the start of an array, you can issue reset, which also returns the value of that element. Examples of how to use this function are:

reset($fred); // Throw away return value
$item = reset($fred); // Keep first element of the array in $item

9. end

As with reset, you can move PHP’s internal array pointer to the final element in an array using the end function, which also returns the value of the element, and can be used as in these examples:

$item = end($fred);

This chapter concludes your basic introduction to PHP, and you should now be able to write quite complex programs using the skills you have learned. In the next chapter, we’ll look at using PHP for common, practical tasks


PHP  Array Shorting

In this section, we will go through the following PHP array sort functions:

  • sort() – sort arrays in ascending order
  • rsort() – sort arrays in descending order
  • asort() – sort associative arrays in ascending order, according to the value
  • ksort() – sort associative arrays in ascending order, according to the key
  • arsort() – sort associative arrays in descending order, according to the value
  • krsort() – sort associative arrays in descending order, according to the key

Sort Array in Ascending Order – sort()

The following example sorts the elements of the $fred array in ascending alphabetical order:

$fred = array("Volvo", "BMW", "Toyota");

Now Try yourself,  every single sorting function