Skip to content

Commit 0719035

Browse files
committed
Add ValueError for invalid mode in count()
Closes GH-5106
1 parent 4281c2a commit 0719035

File tree

3 files changed

+50
-20
lines changed

3 files changed

+50
-20
lines changed

ext/standard/array.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -764,6 +764,11 @@ PHP_FUNCTION(count)
764764
Z_PARAM_LONG(mode)
765765
ZEND_PARSE_PARAMETERS_END();
766766

767+
if (mode != COUNT_NORMAL && mode != COUNT_RECURSIVE) {
768+
zend_value_error("Mode value is invalid");
769+
RETURN_THROWS();
770+
}
771+
767772
switch (Z_TYPE_P(array)) {
768773
case IS_NULL:
769774
/* Intentionally not converted to an exception */
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
--TEST--
2+
Test count() function : invalid modes in weak type mode
3+
--FILE--
4+
<?php
5+
6+
$modes = [
7+
COUNT_NORMAL,
8+
COUNT_RECURSIVE,
9+
0,
10+
1,
11+
-1,
12+
-1.45,
13+
2,
14+
TRUE,
15+
FALSE,
16+
NULL,
17+
];
18+
19+
foreach ($modes as $mode) {
20+
try {
21+
var_dump(count([], $mode));
22+
} catch (\ValueError $error) {
23+
echo $error->getMessage() . \PHP_EOL;
24+
}
25+
}
26+
?>
27+
--EXPECT--
28+
int(0)
29+
int(0)
30+
int(0)
31+
int(0)
32+
Mode value is invalid
33+
Mode value is invalid
34+
Mode value is invalid
35+
int(0)
36+
int(0)
37+
int(0)

ext/standard/tests/array/count_recursive.phpt

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -104,14 +104,10 @@ echo "\n-- Testing count() on arrays containing references --\n";
104104
$arr = array(1, array("a", "b", "c"));
105105
$arr[2] = &$arr[1];
106106

107-
$mode_arr = array( COUNT_NORMAL, COUNT_RECURSIVE, 0, 1, -1, -1.45, 2, TRUE,
108-
FALSE, NULL);
109-
for( $i =0; $i < count( $mode_arr ); $i++) {
110-
echo "For mode '$mode_arr[$i]' count is => ";
111-
var_dump(count($arr, $mode_arr[$i]));
112-
}
113-
114-
echo "\nDone";
107+
echo "Count normal" . \PHP_EOL;
108+
var_dump(count($arr, COUNT_NORMAL));
109+
echo "Count recursive" . \PHP_EOL;
110+
var_dump(count($arr, COUNT_RECURSIVE));
115111

116112
/* closing the resource handles */
117113
fclose( $resource1 );
@@ -209,15 +205,7 @@ COUNT_NORMAL: should be 3, is 3
209205
int(2)
210206

211207
-- Testing count() on arrays containing references --
212-
For mode '0' count is => int(3)
213-
For mode '1' count is => int(9)
214-
For mode '0' count is => int(3)
215-
For mode '1' count is => int(9)
216-
For mode '-1' count is => int(3)
217-
For mode '-1.45' count is => int(3)
218-
For mode '2' count is => int(3)
219-
For mode '1' count is => int(9)
220-
For mode '' count is => int(3)
221-
For mode '' count is => int(3)
222-
223-
Done
208+
Count normal
209+
int(3)
210+
Count recursive
211+
int(9)

0 commit comments

Comments
 (0)