Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate the sum of integers from arrays

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading