]> granicus.if.org Git - php/blob
ff88d7a7f8
[php] /
1 --TEST--
2 Test array_filter() function : usage variations - using the array keys inside 'callback'
3 --FILE--
4 <?php
5 /* Prototype  : array array_filter(array $input [, callback $callback [, bool $use_type = ARRAY_FILTER_USE_VALUE]])
6  * Description: Filters elements from the array via the callback.
7  * Source code: ext/standard/array.c
8 */
9
10 /*
11 * Using array keys as an argument to the 'callback'
12 */
13
14 echo "*** Testing array_filter() : usage variations - using array keys in 'callback' ***\n";
15
16 $input = array(0, 1, -1, 10, 100, 1000, 'Hello', null);
17 $small = array(123);
18
19 function dump($value, $key)
20 {
21   echo "$key = $value\n";
22 }
23
24 var_dump( array_filter($input, 'dump', true) );
25
26 echo "*** Testing array_filter() : usage variations - 'callback' filters based on key value ***\n";
27
28 function dump2($value, $key)
29 {
30   return $key > 4;
31 }
32
33 var_dump( array_filter($input, 'dump2', true) );
34
35 echo "*** Testing array_filter() : usage variations - 'callback' expecting second argument ***\n";
36
37 try {
38     var_dump( array_filter($small, 'dump', false) );
39 } catch (Throwable $e) {
40     echo "Exception: " . $e->getMessage() . "\n";
41 }
42
43 echo "*** Testing array_filter() with various use types ***\n";
44
45 $mixed = array(1 => 'a', 2 => 'b', 'a' => 1, 'b' => 2);
46
47 var_dump(array_filter($mixed, 'is_numeric', ARRAY_FILTER_USE_KEY));
48
49 var_dump(array_filter($mixed, 'is_numeric', 0));
50
51 try {
52     var_dump(array_filter($mixed, 'is_numeric', ARRAY_FILTER_USE_BOTH));
53 } catch (TypeError $e) {
54     echo $e->getMessage(), "\n";
55 }
56
57 echo "Done"
58 ?>
59 --EXPECT--
60 *** Testing array_filter() : usage variations - using array keys in 'callback' ***
61 0 = 0
62 1 = 1
63 2 = -1
64 3 = 10
65 4 = 100
66 5 = 1000
67 6 = Hello
68 7 = 
69 array(0) {
70 }
71 *** Testing array_filter() : usage variations - 'callback' filters based on key value ***
72 array(3) {
73   [5]=>
74   int(1000)
75   [6]=>
76   string(5) "Hello"
77   [7]=>
78   NULL
79 }
80 *** Testing array_filter() : usage variations - 'callback' expecting second argument ***
81 Exception: Too few arguments to function dump(), 1 passed and exactly 2 expected
82 *** Testing array_filter() with various use types ***
83 array(2) {
84   [1]=>
85   string(1) "a"
86   [2]=>
87   string(1) "b"
88 }
89 array(2) {
90   ["a"]=>
91   int(1)
92   ["b"]=>
93   int(2)
94 }
95 is_numeric() expects exactly 1 parameter, 2 given
96 Done