Skip to content

Instantly share code, notes, and snippets.

@javorszky
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javorszky/9110574 to your computer and use it in GitHub Desktop.
Save javorszky/9110574 to your computer and use it in GitHub Desktop.
Why is $and not 1?
<?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
)
)
*/
@javorszky
Copy link
Author

The first time reduce_and is called, $a === NULL after looking at it with gettype. I'm lost as to why.

@javorszky
Copy link
Author

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