Prev | Current Page 229 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Its prototype follows:
mixed array_sum(array array)
If other datatypes (a string, for example) are found in the array, they will be ignored. An
example follows:
$grades = array(42,"hello",42);
$total = array_sum($grades);
print $total;
?>
This returns the following:
84
162 CHAPTER 5 ?–  ARRAYS
Subdividing an Array
The array_chunk() function breaks input_array into a multidimensional array that
includes several smaller arrays consisting of size elements. Its prototype follows:
array array_chunk(array array, int size [, boolean preserve_keys])
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.


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