array_sum计算数组元素的和。
- 如果元素的值都是整数,则返回整数结果
- 如果元素的值有浮点数,则返回浮点数结果
- false,null被转换成 0
- true转成1
- 数组和对象被忽略不参与计算
- 资源句柄被转换成相应的整型值
- 字符串被转成相应的数字,不能转换的跳过
/**
* Calculate the sum of values in an array
* @link https://php.net/manual/en/function.array-sum.php
* @param array $array <p>
* The input array.
* </p>
* @return int|float the sum of values as an integer or float.
*/
function array_sum(array $array) { }
示例:注意看下面的结果,结合上面的几条结论
$fp = fopen(__DIR__.'/order.php', 'r');
var_dump($fp); //resource(5) of type (stream)
$array = [
true, //1
false, //0
null, //0
$fp, //5
2.5, //2.5
[],
'a',
'3', //3
new \stdClass()
];
$result = array_sum($array);
var_dump($result);
//结果
//double(11.5)
?扩展阅读:
array_sum函数C源码实现
PHP_FUNCTION(array_sum)
{
zval *input,
*entry,
entry_n;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(input)
ZEND_PARSE_PARAMETERS_END();
ZVAL_LONG(return_value, 0);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(input), entry) {
if (Z_TYPE_P(entry) == IS_ARRAY || Z_TYPE_P(entry) == IS_OBJECT) {
continue;
}
ZVAL_COPY(&entry_n, entry);
convert_scalar_to_number(&entry_n);
fast_add_function(return_value, return_value, &entry_n);
} ZEND_HASH_FOREACH_END();
}
数组元素中的数据转换成标量数据实现?
static void ZEND_FASTCALL _convert_scalar_to_number(zval *op, zend_bool silent, zend_bool check) /* {{{ */
{
try_again:
switch (Z_TYPE_P(op)) {
case IS_REFERENCE:
zend_unwrap_reference(op);
goto try_again;
case IS_STRING:
{
zend_string *str;
str = Z_STR_P(op);
if ((Z_TYPE_INFO_P(op)=is_numeric_string(ZSTR_VAL(str), ZSTR_LEN(str), &Z_LVAL_P(op), &Z_DVAL_P(op), silent ? 1 : -1)) == 0) {
ZVAL_LONG(op, 0);
if (!silent) {
zend_error(E_WARNING, "A non-numeric value encountered");
}
}
zend_string_release_ex(str, 0);
break;
}
case IS_NULL:
case IS_FALSE:
ZVAL_LONG(op, 0);
break;
case IS_TRUE:
ZVAL_LONG(op, 1);
break;
case IS_RESOURCE:
{
zend_long l = Z_RES_HANDLE_P(op);
zval_ptr_dtor(op);
ZVAL_LONG(op, l);
}
break;
case IS_OBJECT:
{
zval dst;
convert_object_to_type(op, &dst, _IS_NUMBER, convert_scalar_to_number);
if (check && UNEXPECTED(EG(exception))) {
return;
}
zval_ptr_dtor(op);
if (Z_TYPE(dst) == IS_LONG || Z_TYPE(dst) == IS_DOUBLE) {
ZVAL_COPY_VALUE(op, &dst);
} else {
ZVAL_LONG(op, 1);
}
}
break;
}
}
|