Using Array Functions

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:

<?php
$products = array(
		'copier' => "Copier & Multipurpose",
		'inkjet' => "Inkjet Printer",
		'laser' => "Laser Printer",
		'photo' => "Photographic Paper");

echo (is_array($products)) ? "Is an array" : "Is not an array";
?>

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:

<?php
$products = array(
		'copier' => "Copier & Multipurpose",
		'inkjet' => "Inkjet Printer",
		'laser' => "Laser Printer",
		'photo' => "Photographic Paper");

echo (count($products));
?>

3. sort()

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

<?php
$products = array(
		"Photographic Paper",
		"Inkjet Printer",
		"Laser Printer",
		"Copier & Multipurpose"
		);

sort($products);
var_dump($products);
?>

4. 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 a sentence up into an array containing all its words, as in following example

<?php
$temp = explode(' ', "quick brown red fox jumps over the ");
print_r($temp);
?>