I’m wondering if there is another way to calculate the sum of integers. Are there any built-in functions, or different ways to count this?
I create an empty array
$arr=array(14, 13,"Cat",16,"Dog", 13.8, 14.5);
$arr2=array();
I found an empty integer and pushed into empty array
foreach ($arr as $val){
if(is_int($val)){
array_push($arr2, $val);
} }
and then i summed all integer
$sum=0;
foreach($arr2 as $val2){
$sum += $val2;
}
echo $sum;
Is my way correct?
>Solution :
Your way of calculating the sum of these integers is basically okay.
Take a look at array_filter() and array_sum() function in the php-docs to get rid of these foreach-loops:
$arr = array(14, 13,"Cat",16,"Dog", 13.8, 14.5);
$arr2 = array_filter($arr, 'is_int');
$sum = array_sum($arr2);
echo $sum;