In this section I introduce a number of array functions that perhaps don’t easily fall into one of the prior sections, but are nonetheless quite useful.
array_rand()
mixed array_rand(array input_array [, int num_entries])
The array_rand() function will return one or more keys found in input_array. If you omit the optional num_entries parameter, only one random value will be returned. If num_entries is set to greater than one, that many keys will be returned. An example follows:
$states = array("Ohio" => "Columbus", "Iowa" => "Des Moines","Arizona" => "Phoenix");
$randomStates = array_rand($states, 2);
print_r($randomStates);
This returns:
===========================================================
Array ( [0] => Arizona [1] => Ohio ) ===========================================================
array_chunk()
array array_chunk(array input_array, int size [, boolean preserve_keys])
The array_chunk() function breaks input_array into a multidimensional array consisting of several smaller arrays consisting of size elements. If the input array can’t be evenly divided by size, the last array will consist of fewer than size elements. Enabling the optional parameter preserve_keys will preserve each value’s corresponding key. Omitting or disabling this parameter results in numerical indexing starting from zero for each array. An example follows:
$cards = array("jh","js","jd","jc","qh","qs","qd","qc",
"kh","ks","kd","kc","ah","as","ad","ac");
// shuffle the cards
shuffle($cards);
// Use array_chunk() to divide the cards into four equal "hands"
$hands = array_chunk($cards, 4);
print_r($hands);
This returns the following (your results will vary because of the shuffle):
===========================================================
Array ( [0] => Array ( [0] => jc [1] => ks [2] => js [3] => qd )
[1] => Array ( [0] => kh [1] => qh [2] => jd [3] => kd )
[2] => Array ( [0] => jh [1] => kc [2] => ac [3] => as )
[3] => Array ( [0] => ad [1] => ah [2] => qc [3] => qs ) )============================================================
Summary
Arrays play an indispensable role in programming, and are ubiquitous in every imaginable type of application, Web-based or not. The purpose of this chapter was to bring you up to speed regarding many of the PHP functions that will make your programming life much easier as you deal with these arrays.
The next chapter focuses on yet another very important topic: object-oriented programming. This topic has a particularly special role in PHP 5, because the process has been entirely redesigned for this major release.