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

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:

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

<?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?

>Solution :

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
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