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?
CodePudding user response:
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