2
I have some scripts that do some calculations with data coming from a form, and to do the sum of all they created another file where I do the sum:
include "varios.php";
$total = $var1 + $var2 + $var3; /// etc
However, I want you to add only the variables that are set, so I tried:
$total = isset($var1) + isset($var2) + isset($var3);
But from what I understand, so he considers 1
if it is set, and 0
if it is not, no matter the value coming from the form.
As I asked this question, I was able to solve it (but I don’t know if in the best way), so:
if (!isset($var1)){
$var1 = 0;
}
So I don’t have any more problems, but then I was wondering why the first one didn’t work. Doing that way I think I’ve turned the type of variable into boolean... Is that it? How it occurs, and why?
If you are not mistaken it adds up the results of isset, which can be only 1 or 0. The expression would be something like:
$total = 1 + 0 + 1;
or similar– rray
Ah, so I didn’t turn the variable into boolean... if I use after, without the
isset
, will come the right value... let see rsrs– gustavox
Use Empty() to check if there is a value, that way you did it will not work because the function will return a boolean and not its value if it exists
– Gabriel Rodrigues
Your problem are even variables or are in an array?
– rray
So @rray as I tried (but I don’t know if I could) explain in the comment of the other answer, what happens is that I mount the form dynamically (the person chooses from a list which calculations they want to do together), and then I use a variable
$_SESSION['calculoX']
for example to identify that that calculation was chosen, so at some point I make aif ($_SESSION['calculoX'])
to know if the script will be included in the result page, and if false does not include. Only when he was going to sum all the values (including even those that were not selected), he received the error Undefined index.– gustavox
I don’t know if it was clear... but there was nothing with array or even with
empty()
(that I use, by the way, in the declaration of variables) as appeared in the other answer and in the comment of @Gabrielrodrigues (thanks anyway man! )... The problem is I cast the same boolean...– gustavox