Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Semi Basic If/then question 1

Status
Not open for further replies.

Zych

IS-IT--Management
Apr 3, 2003
313
0
0
US
Hello All,

I want to check if a number is between other numbers. For example I would want the following:

Lets say $x1=8

Then I would want to check if $x1 is between 11 - 46, if it is not then do the else. How would I write this? Can I use an and in the if statement? for example

if($x1 > 11 and $x1 < 46) { put the other code here}

or is there another way?


In the above example it would fail, if $x1=16 then it would pass.

Thanks,

Zych
 
Thanks! Works great.
 
Another thing is I would write the inequalities the other way so that the constants are on the other side (espcally when checking for equals). The reason is leaving off an equals will cause an assignment:
Code:
if($x == 1) // is fine for checking equality, 
            //   but leave out and equal and you get: 
if($x = 1)  // legal, but not what your looking for
            // moreover, it will "work," 
            // in that the page will load and seem fine, 
            // but this statment isn't the inequality we
            // were looking for, and it has a horrible 
            // side effect.  This error is hard to catch 
            // (in that it does the right thing 1/2 at this             
            // point -- and fails slowly),
            // can cause horrible propagation 
            // (say we store $x to the database, and is
            // all too common because we are humans and
            // typeing can be rather error prone.      
            // Because we all mistype every now and again
            // a good practive to get into is flop the 
            // constant and the variable, so the constant is
            // is always on the left hand side:
if(1 == $x) // is great, and if we lose an equals we get:
if(1 = $x)  // illegal, which will display an error 
            // that your trying to assign to a constant, and
            // a line number for where the 
            // error actually happens.

Just a helpful defensive hint. Applied to your question:
Code:
// Exclusive
if(11 < $x1 and 46 > $x1)
{
}
else
{
}

// Or inclusive:

if(11 <= $x1 and 46 >= $x1)
{
}
else
{
}

[plug=shameless]
[/plug]
 
Hey jstreich,

Good point, I never really thought of that. And being new to PHP I have left off one of the = signs many times. Though this does help me in the debugging, it does take up time.

- Zych
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top