Page 1 of 1

Checking Variables!

Posted: Thu Feb 19, 2004 6:43 am
by Perfidus
Hello!

I have a group of variables and I have to check if they are !=0:

$ene1t
$ene2t
$ene3t
$ene4t
$ene5t
$feb1t
$feb2t
$feb3t

As soon as one condition is true (!=0) I want to take the value of this one, doesn't matter if more of them matches the condition, I only need the value of the first one.
How can I arrange that?

Posted: Thu Feb 19, 2004 7:46 am
by Dr Evil
Will this list of variables get any longer ?

Posted: Thu Feb 19, 2004 8:10 am
by Perfidus
as soon as I get the value of the first that matches condition, I do not need them anymore.

Posted: Thu Feb 19, 2004 8:22 am
by Dr Evil
What I mean is will there be a :
$mar1t
$mar2t
$mar3t
$mar4t
$abr1t
$abr2t
$abr3t
$abr4t
...

?

Posted: Thu Feb 19, 2004 8:55 am
by liljester
sounds like a good use for an array instead of lots of variables.

Posted: Thu Feb 19, 2004 9:08 am
by Dr Evil
I havent found a answer yet, but that is the way I was going, yes. Do you have a suggestion ?

Posted: Thu Feb 19, 2004 11:20 am
by Perfidus
This can show us if a variable matches condition, but what I need is to echo the the first variable that matches. (It doesnt matter if 5 variables matches or not, just the first one that does)

Code: Select all

<?php
$variables = array($ene1t, $ene2t, $ene3t, $ene4t, $ene5t, $feb1t, $feb2t,$feb3t ); 

for ($i =0; $i < count($variables); $i++) 
{ 
  if (!is_null($variables[$i])) 
  { 
     echo "some stuff"; 
     break(); 
  } 
}
?>

Posted: Thu Feb 19, 2004 1:54 pm
by Dr Evil
You can try counting backwards:

Code: Select all

<?php
$variables = array($ene1t, $ene2t, $ene3t, $ene4t, $ene5t, $feb1t, $feb2t,$feb3t ); 

for ($i = count($variables)-1; $i >= 0; $i--) 
{ 
  if ($variables[$i]!=0) 
  { 
     $result= $variables[$i];     
  } 
} 
echo $result;
?>

Posted: Thu Feb 19, 2004 2:17 pm
by McGruff
Note the difference between if($var != 0) and if($var !== 0). Nulls, boolean false, "integer strings", and an empty string could give false positives.

Code: Select all

$var = 1;               // both true
$var = 0;               // both false
$var = '0';             // != false, !== true (eg POST values are string type)
$var = '';              // != false, !== true
$var = true;            // both true
$var = false;           // != false, !== true
$var = null;            // != false, !== true

Posted: Thu Feb 19, 2004 2:19 pm
by Dr Evil
Thanks McGruff.

I discover something interesting here everyday !!!

Posted: Thu Feb 19, 2004 2:25 pm
by McGruff
That level of precision isn't necessarily required - depends what the range of possible values actually are.

$_POST can easily catch you out though - everything is a string even if it's a number...