How to add a PHP variable only if it is set?

2

I have some scripts that do some calculations with data coming from a form, and to make the sum of them all I created another file where I make the sum:

include "varios.php";

$total = $var1 + $var2 + $var3; /// etc

However, I want to only add the variables that have been set, so I tried:

$total = isset($var1) + isset($var2) + isset($var3);

But, from what I've noticed, it looks like 1 if set, and 0 if not, regardless of the value coming from the form.

As I was asking this question I have already been able to solve (but I do not know if in the best way), like this:

if (!isset($var1)){
    $var1 = 0;
}

So I do not have any more problems, but then I was in doubt because the first form did not work. Doing that way I think I made the variable type boolean ... Is this? How does this occur, and why?

    
asked by anonymous 30.10.2015 / 00:32

3 answers

3

PHP does cast to boolean pretty much the time ie the expression is summing the results of isset() which can be 1 or 0.

<?php
   $var = 5;
   $var2 = 4;

   $total = isset($var) + isset($var2) + isset($var3);
   echo $total;

The output is 2 and not 9 as expected, php understood the expression as: 1+1+0

Ideone example

    
30.10.2015 / 01:05
3

You can simply set the% cos_de% value this way when handling values coming from forms. Example:

$var1 = isset($_POST['number1']) ? $_POST['number1'] : 0;
    
30.10.2015 / 00:58
2

There are several means to solve.

See an example using variable variables and array_sum()

$sum = array();
$v = 'var1'; $sum[] = (!isset($$v)? 0 : $$v);
$v = 'var2'; $sum[] = (!isset($$v)? 0 : $$v);
$v = 'var2'; $sum[] = (!isset($$v)? 0 : $$v);

$total = array_sum($sum);

echo $total;
    
30.10.2015 / 05:07