Last active
October 7, 2015 03:48
-
-
Save giovanniramos/3100679 to your computer and use it in GitHub Desktop.
Returns the sum of occurrences, in an array of a given condition satisfied
This file contains 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 | |
/** | |
* Returns the sum of occurrences, in an array of a given condition satisfied | |
* | |
* @param mixed $value The value or array to be evaluated | |
* @param string $operator Operator of evaluation | |
* @param string $conditional Conditional assignment | |
* @return integer | |
* @link https://gist.github.com/3100679 | |
* | |
* */ | |
function countWhere($value = 1, $operator = '==', $conditional = 1) | |
{ | |
$array = is_array($value) ? $value : (array) $value; | |
$operator = !in_array($operator, array('<', '>', '<=', '>=', '==', '!=')) ? '==' : $operator; | |
$i = 0; | |
foreach ($array as $current) { | |
$match = null; | |
eval('$match = (bool)("' . $current . '"' . $operator . '"' . $conditional . '");'); | |
$i = $match ? ++$i : $i; | |
} | |
return $i; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment