Skip to content

Instantly share code, notes, and snippets.

@Girgias Girgias/array.c Secret
Created Nov 22, 2019

Embed
What would you like to do?
New (better?) count()
/* {{{ proto int count(mixed var [, int mode])
Count the number of elements in a variable (usually an array) */
PHP_FUNCTION(count)
{
HashTable *array = NULL;
zend_long mode = COUNT_NORMAL;
zend_object *countable;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "h!|l", &array, &mode) == SUCCESS) {
if (array == NULL) {
/* Intentionally not converted to an exception */
php_error_docref(NULL, E_DEPRECATED, "Passing null is deprecated");
RETURN_LONG(0);
}
zend_long cnt;
if (mode == COUNT_NORMAL) {
cnt = zend_array_count(array);
} else if (mode == COUNT_RECURSIVE) {
cnt = php_count_recursive(array);
} else {
zend_value_error("Mode value is invalid");
return;
}
RETURN_LONG(cnt);
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "O|l", &countable, zend_ce_countable, &mode) == SUCCESS) {
if (mode != COUNT_NORMAL && mode != COUNT_RECURSIVE) {
zend_value_error("Mode value is invalid");
return;
}
zval retval;
zend_call_method_with_0_params(countable, NULL, NULL, "count", &retval);
if (Z_TYPE(retval) != IS_UNDEF) {
RETVAL_LONG(zval_get_long(&retval));
zval_ptr_dtor(&retval);
return;
}
zval_ptr_dtor(&retval);
RETURN_LONG(1);
return;
} else {
zend_type_error("Parameter must be an array or an object that implements Countable");
return;
}
}
/* }}} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.