Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. count() / array_sum() / range()

count() / array_sum() / range()

Since: PHP 4(2000)

Functions for counting array elements, computing totals, generating sequential arrays, and randomly manipulating arrays.

Syntax

count(array, mode);

array_sum(array);

array_product(array);

// Generates a sequential array.
range(start, end, step);

// Shuffles the elements of an array in random order.
shuffle(array);

// Returns one or more random keys from an array.
array_rand(array, count);

Function List

FunctionDescription
count($array, $mode)Returns the number of elements in an array. Pass COUNT_RECURSIVE as the second argument to recursively count all elements in a multidimensional array.
array_sum($array)Returns the sum of all values in an array. Non-numeric values are treated as 0.
array_product($array)Returns the product of all values in an array. Returns 1 for an empty array.
range($start, $end, $step)Generates an array containing a sequence of values from start to end. Also works with strings.
shuffle($array)Randomly reorders the elements of an array. Keys are re-indexed starting from 0.
array_rand($array, $num)Returns one or more random keys from an array.

Sample Code

count.php
<?php
$members = ['Kiryu Kazuma', 'Majima Goro', 'Akiyama Shun', 'Nishikiyama Akira'];
echo count($members); // Outputs "4".

// Calculate the sum of an array.
$prices = [150, 80, 300, 200];
echo array_sum($prices); // Outputs "730".

// Calculate the product of an array.
$nums = [2, 3, 4];
echo array_product($nums); // Outputs "24".

// Calculate the average.
$scores = [85, 92, 78, 95, 88];
$average = array_sum($scores) / count($scores);
echo $average; // Outputs "87.6".

// Generate a sequential array.
$one_to_ten = range(1, 10);
print_r($one_to_ten); // Generates an array from 1 to 10.

// Generate an array of even numbers using a step value.
$evens = range(2, 10, 2);
print_r($evens); // Results in [2, 4, 6, 8, 10].

// Generate an array of letters.
$alphabet = range('A', 'F');
print_r($alphabet); // Results in ['A', 'B', 'C', 'D', 'E', 'F'].

// Shuffle an array randomly.
$cards = range(1, 5);
shuffle($cards);
print_r($cards); // Elements are in a random order (changes every run).

// Pick a random element from an array.
$fighters = ['Kiryu Kazuma', 'Majima Goro', 'Akiyama Shun', 'Saejima Taiga', 'Nishikiyama Akira'];
$key = array_rand($fighters);
echo $fighters[$key]; // Outputs one random fighter name.

// Pick multiple random keys.
$keys = array_rand($fighters, 2);
print_r($keys); // Returns two randomly selected keys.

Running the code produces the following output:

php count.php
4
730
24
87.6
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => E
    [5] => F
)
# shuffle() result is random. It changes every run. Example:
Array
(
    [0] => 3
    [1] => 1
    [2] => 5
    [3] => 2
    [4] => 4
)
Kiryu Kazuma
# array_rand() result is random. It changes every run. Example:
Array
(
    [0] => 0
    [1] => 3
)

count() works on objects, but be careful with non-arrays

Since PHP 7.2, passing a value that is neither an array nor a Countable object to count() triggers a warning. Avoid passing strings or numbers.

<?php
$members = ['Kiryu Kazuma', 'Majima Goro', 'Akiyama Shun'];
echo count($members); // Correct: outputs "3".

// Passing a non-array value triggers a warning in PHP 7.2+.
$name = 'Kiryu Kazuma';
// echo count($name); // Warning: count(): Parameter must be an array or an object that implements Countable

shuffle() re-indexes keys from 0

shuffle() modifies the original array directly and re-indexes all numeric keys starting from 0. Using it on an associative array destroys the original keys.

<?php
$fighters = [
	'a' => 'Kiryu Kazuma',
	'b' => 'Majima Goro',
	'c' => 'Akiyama Shun',
];

shuffle($fighters); // Keys are re-indexed to 0, 1, 2.
print_r($fighters);
// Array
// (
//     [0] => Majima Goro
//     [1] => Kiryu Kazuma
//     [2] => Akiyama Shun
// )
// The original keys 'a', 'b', 'c' are gone.

array_rand() returns keys, not values

array_rand() returns the key(s) of the randomly selected element(s), not the values themselves. You need to use the returned key to access the value in the array.

<?php
$fighters = ['Kiryu Kazuma', 'Majima Goro', 'Akiyama Shun', 'Nishikiyama Akira', 'Saejima Taiga'];

$key = array_rand($fighters);
echo $key; // Outputs a key (e.g., "2")
echo $fighters[$key]; // Use the key to get the value (e.g., "Akiyama Shun")

// Getting multiple keys
$keys = array_rand($fighters, 2);
foreach ($keys as $k) {
	echo $fighters[$k] . "\n"; // Use each key to access the value.
}

Practical Patterns

Random selection logic

Randomly picking one or more members from a list.

<?php
function drawLottery(array $members, int $count = 1): array {
	$keys = array_rand($members, min($count, count($members)));
	$results = [];
	if (!is_array($keys)) {
		$keys = [$keys];
	}
	foreach ($keys as $k) {
		$results[] = $members[$k];
	}
	return $results;
}

$members = ['Kiryu Kazuma', 'Majima Goro', 'Akiyama Shun', 'Nishikiyama Akira', 'Saejima Taiga'];
$winners = drawLottery($members, 2);
foreach ($winners as $winner) {
	echo $winner . " won!\n";
}
sample_lottery.php
php sample_lottery.php
Akiyama Shun won!
Saejima Taiga won!

Array statistics

Getting the total, average, max, and min of an array all at once.

<?php
$scores = ['Kiryu Kazuma' => 95, 'Majima Goro' => 88, 'Akiyama Shun' => 72, 'Nishikiyama Akira' => 91, 'Saejima Taiga' => 84];

echo "Count: "   . count($scores) . "\n";
echo "Total: "   . array_sum($scores) . "\n";
echo "Average: " . (array_sum($scores) / count($scores)) . "\n";
echo "Max: "     . max($scores) . "\n";
echo "Min: "     . min($scores) . "\n";
sample_stats.php
php sample_stats.php
Count: 5
Total: 430
Average: 86
Max: 95
Min: 72

Notes

count() can be used not only on arrays but also on objects that implement the Countable interface. Since PHP 7.2, passing a value that is neither an array nor a Countable object triggers a warning. The alias sizeof() also exists, but count() is more commonly used.

array_sum() also works on the values of associative arrays. Non-numeric values are treated as 0. Combining array_sum() and count() lets you calculate an average.

range() can generate sequences of strings as well as numbers. Passing a negative step value creates a descending array.

shuffle() modifies the original array in place and re-indexes keys starting from 0. array_rand() returns keys, not values, so you need to use the returned key to access the corresponding array element. For aggregating array values, see array_reduce().

If you find any errors or copyright issues, please .