Skip to content

Instantly share code, notes, and snippets.

@salathe
Created May 11, 2012 10:29
Show Gist options
  • Select an option

  • Save salathe/2658848 to your computer and use it in GitHub Desktop.

Select an option

Save salathe/2658848 to your computer and use it in GitHub Desktop.
/* {{{ proto int count(mixed var [, int mode])
Count the number of elements in a variable (usually an array) */
PHP_FUNCTION(count)
{
zval *array;
long mode = COUNT_NORMAL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &array, &mode) == FAILURE) {
return;
}
switch (Z_TYPE_P(array)) {
case IS_NULL:
RETURN_LONG(0);
break;
case IS_ARRAY:
RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC));
break;
case IS_OBJECT: {
#ifdef HAVE_SPL
zval *retval;
#endif
/* first, we check if the handler is defined */
if (Z_OBJ_HT_P(array)->count_elements) {
RETVAL_LONG(1);
if (SUCCESS == Z_OBJ_HT(*array)->count_elements(array, &Z_LVAL_P(return_value) TSRMLS_CC)) {
return;
}
}
#ifdef HAVE_SPL
/* if not and the object implements Countable we call its count() method */
if (Z_OBJ_HT_P(array)->get_class_entry && instanceof_function(Z_OBJCE_P(array), spl_ce_Countable TSRMLS_CC)) {
zend_call_method_with_0_params(&array, NULL, NULL, "count", &retval);
if (retval) {
convert_to_long_ex(&retval);
RETVAL_LONG(Z_LVAL_P(retval));
zval_ptr_dtor(&retval);
}
return;
}
#endif
}
default:
RETURN_LONG(1);
break;
}
}
/* }}} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment