Last active
August 29, 2015 13:56
-
-
Save javorszky/9110574 to your computer and use it in GitHub Desktop.
Why is $and not 1?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if( !function_exists('es_preit') ) { | |
function es_preit( $obj, $echo = true ) { | |
if( $echo ) { | |
echo '<pre>'; | |
print_r( $obj ); | |
echo '</pre>'; | |
} else { | |
return '<pre>' . print_r( $obj, true ) . '</pre>'; | |
} | |
} | |
} | |
$conds = array(1,1); | |
function reduce_and($a, $b) { | |
$a *= $b; | |
return $a; | |
} | |
$and = array_reduce($conds, 'reduce_and'); | |
es_preit(array( | |
'this is $conds' => $conds, | |
'this is $and' => array( | |
$and, gettype($and) | |
) | |
)); | |
/* | |
Prints: | |
Array | |
( | |
[this is $conds] => Array | |
( | |
[0] => 1 | |
[1] => 1 | |
) | |
[this is $and] => Array | |
( | |
[0] => 0 | |
[1] => integer | |
) | |
) | |
*/ |
SOLVED.
For anyone wondering, array_reduce
needs to work on arrays that have only one element, and it'd be grand if in those cases PHP wouldn't die. Thus the initial value is important. If not set, it's null
, and null * 1 = null
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The first time
reduce_and
is called,$a === NULL
after looking at it withgettype
. I'm lost as to why.