Skip to content

Instantly share code, notes, and snippets.

@giovanniramos
Last active October 7, 2015 03:48
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 giovanniramos/3100679 to your computer and use it in GitHub Desktop.
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
<?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