Home > database >  Easy way to avoid string addition in php
Easy way to avoid string addition in php

Time:06-30

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?

CodePudding user response:

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

CodePudding user response:

You might need to use intval() function. intval will get an integer value from a variable, if non-numeric characters were found, it will return 0.

Example:

$total = intval($val1)   intval($val2)   intval($val3)   intval($val4)   intval($val5)   intval($val6);
// $total = 11

Also unless you have hundreds of thousands of values, I don't think it will take more than a few seconds.

  •  Tags:  
  • php
  • Related