Prev | Current Page 228 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


Returning a Random Set of Keys
The array_rand() function will return a random number of keys found in an array. Its
prototype follows:
mixed array_rand(array array [, int num_entries])
If you omit the optional num_entries parameter, only one random value will be
returned. You can tweak the number of returned random values by setting num_entries
accordingly. An example follows:
$states = array("Ohio" => "Columbus", "Iowa" => "Des Moines",
"Arizona" => "Phoenix");
$randomStates = array_rand($states, 2);
print_r($randomStates);
This returns the following (your output may vary):
Array ( [0] => Arizona [1] => Ohio )
Shuffling Array Elements
The shuffle() function randomly reorders an array. Its prototype follows:
void shuffle(array input_array)
CHAPTER 5 ?–  ARRAYS 161
Consider an array containing values representing playing cards:
$cards = array("jh","js","jd","jc","qh","qs","qd","qc",
"kh","ks","kd","kc","ah","as","ad","ac");
// shuffle the cards
shuffle($cards);
print_r($positions);
This returns something along the lines of the following (your results will vary
because of the shuffle):
Array ( [0] => js [1] => ks [2] => kh [3] => jd
[4] => ad [5] => qd [6] => qc [7] => ah
[8] => kc [9] => qh [10] => kd [11] => as
[12] => ac [13] => jc [14] => jh [15] => qs )
Adding Array Values
The array_sum() function adds all the values of input_array together, returning the
final sum.


Pages:
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240