Mughal Gee Mughal Gee - 3 months ago 7
PHP Question

Filter string from inside an array

I tried this:-

function sum_array($arr_sum){
$string= "";

$length= count($arr_sum);
$sum= NULL;
if(is_string($arr_sum)){
echo "You cannot use string";
}else{
for($i=0; $i<$length; $i++){
$sum = $sum + $arr_sum[$i];
}
echo " The Sum is ". $sum;
}
}
$array_summation=["string",12.6,25.2,10,12];
sum_array($array_summation);


I want to know what should i do if i want only integer or float value inside an array, and if string come inside array it gives error that no string wanted or something like that

Answer

Try this

function sum_array($arr_sum){   
        $sum = 0;
        foreach($arr_sum as $value){
            if(!is_numeric($value)){
                echo 'Array Contain non numeric data';
                exit;
            }
            $sum += $value;
        }
        echo 'The sum is '.$sum;
    }

    $array_summation=["string",12.6,25.2,10,12];
    sum_array($array_summation);