How to count multiple variables with strlen

170 Views Asked by At

I am looking to count the length of strings in multiple variables and add them together to get the total count.

I have tried strlen but have either messed up the syntax or have not used the proper code.

//$_SESSION['var1'] and $_SESSION['var2'] will each be numbers from -30.0 to 1000.0. I need the lengths of the two variables to be added. I need the negative sign(s) and decimal separators, or dots, to be counted.

$_SESSION['var_array'] = $_SESSION['var1'].$_SESSION['var2'];
$_SESSION['var_count'] = strlen($_SESSION['var_array']);

or

$_SESSION['var_count'] = strlen($_SESSION['var1'])+strlen($_SESSION['var2']);

Various results are observed. Sometimes the correct number IS observed but usually not.

1

There are 1 best solutions below

0
Nigel Ren On

The problem is that just storing numeric values doesn't maintain trailing decimals if they are 0. You could alternatively store them as strings, which will maintain the values exactly as you want them or format the numbers to ensure they contain the right format. The following code shows what I mean...

$_SESSION['var1'] = -30.0;
echo $_SESSION['var1'].PHP_EOL; // Gives -30

$_SESSION['var1'] = number_format($_SESSION['var1'], 1);
echo $_SESSION['var1'].PHP_EOL;  // gives -30.0

$_SESSION['var2'] = "1000.0";
echo $_SESSION['var1'].PHP_EOL;  // gives 1000.0

$_SESSION['var_array'] = $_SESSION['var1'].$_SESSION['var2'];
echo strlen($_SESSION['var_array']);  // gives 11