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

Convert strings to "0" in php

I have a list of strings and some of them have texts in them. Ultimately I want the strings to be added up. The strings that have texts in them, I want to convert them to "0". So what is the right and easy way to do this?

<?php

$str_1 = "4";
$str_2 = "A.I";
$str_3 = "8";
$str_4 = "Sky";
$str_5 = "Sa";

$total = intval ($str_1) + intval ($str_2) + intval ($str_3) + intval ($str_4) + intval ($str_5);

?>

Ofc the above code won’t work. So how does one automatically convert the str2, str3 and str4 to 0?

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

>Solution :

You can achieve this with a function that has a variable-length argument list:

<?php

/*

Question Author: Vika
Question Answerer: Jacob Mulquin
Question: Convert strings to "0" in php
URL: https://stackoverflow.com/questions/74613261/convert-strings-to-0-in-php
Tags: php

*/

function addIfNumeric(...$strings)
{
    $sum = 0;
    foreach ($strings as $string) {
        if (is_numeric($string))
            $sum += $string;
    }
    return $sum;
}

$str_1 = "4";
$str_2 = "A.I";
$str_3 = "8";
$str_4 = "Sky";
$str_5 = "Sa";

$sum = addIfNumeric($str_1, $str_2, $str_3, $str_4, $str_5);

echo $sum . PHP_EOL;

Yields

12
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