我希望计算多个变量中的字符串长度,并将它们加在一起以获得总计数。
我尝试过strlen
,但语法混乱或没有使用正确的代码。
//$_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']);
或
$_SESSION['var_count'] = strlen($_SESSION['var1'])+strlen($_SESSION['var2']);
观察到各种结果。有时会看到正确的数字,但通常不会。
答案 0 :(得分:0)
问题是,如果数字值为0,则仅存储数字值不会保留尾随小数。您也可以将它们存储为字符串,这将完全按照您的要求维护值,或者格式化数字以确保它们包含正确的格式。以下代码显示了我的意思...
$_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