Skip to content
Advertisement

Easy way to avoid string addition in php

This question is an extension of the question asked here – Easy way to avoid string addition in C#. I am looking for similar method to achieve in PHP.

Problem: I have couple of string variables that sometimes have text and other times have integers in them. How do I add these variables when they are integers?

Example:

<?php

$val1 = "1";
$val2 = "2";
$val3 = "3";
$val4 = "k.A";
$val5 = "k.A";
$val6 = "5";

$total = $val1 + $val2 + $val3 + $val4 + $val5 + $val6;

?>

I know the above code will fail because val4 and val5 are strings, what I am looking for is it should avoid adding the above 2 strings and the total should be 11. I can check if the string is an integer or a text but that would take forever if the script I am working on does not have strings as an array. What is the right and easy way to do this?

Advertisement

Answer

Easiest solution is to add all variables to array.

Then apply filter for each elements checking if it’s is_numeric

And then just to array_sum

$val = [
    "1",
    "2",
    "3",
    "k.A",
    "k.A",
    "5",
];

$total = array_sum(array_filter($val, 'is_numeric'));

echo $total; // 11
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement