array functions Flashcards
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 doubt and your code needs to check whether a variable is an array, you can use the is_array function like this:
echo (is_array($fred)) ? “Is an array” : “Is not an array”;
count
To count all the elements in the top level of an array, use a command such as the following:
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:
echo count($fred, 1);
sort
To sort an array:
sort($fred);
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
To sort an array in reverse order:
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);
shuffle
To put an array in random order:
shuffle($cards);
explode
Takes a string containing several items separated by a single character (or a string of characters) and then places each of these items into an array.
$temp = explode(‘ ‘, “This is a sentence with seven words”);
extract
Assigns values of an array to new variables
extract($_GET);
To avoid the possibility of overwriting variables that already exist, you can prefix the new variables:
extract($_GET, EXTR_PREFIX_ALL, ‘fromget’);
compact
The inverse of extract, creates an array from variables and their values:
$contact = compact(‘fname’, ‘sname’, ‘planet’, ‘system’, ‘constellation’);
print_r(compact(explode()));
Printout of a group of variables’s values. Place the names of the variables inside explode separated by a character you choose.
reset
When the foreach… as construct or the each function talks 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 returns the value of that element.
reset($fred); // throw away return value
$item = reset($fred); // keep first element of the array in $item
end
Move PHP’s internal array pointer to the final element in an array, which also returns the value of the element:
end($fred);
$item = end($fred);