Jump to content

How to compare variables


saeed_violinist

Recommended Posts

Hi,

I wonder how we can compare a variable (int) to know is ist bigger or smaller than 2 other int's . I recently wrote a simple code to greet my visitors, shown as below :

[code]
<?php
function Greeting() {

$time = date('G');

    if($time < 4 and $time >=0 ) {
    return "good night";
    } elseif ($time < 11 and $time >= 4 ) {
    return "good morning";
    } elseif ($time < 16 and $time >=11 ) {
    return "good afternoon";
    } elseif ($time >= 16 and $time < 20 ) {
    return "good evening";
    } elseif ($time <=23 and $time >=20 ) {
    return "goodnight";
    } else {
    return "error!";
    }
}
?>
[/code]

o, as you see I know what to do , but the result will not satistify me ! cause when I say "($time < 11 and $time >= 4)" it will contain all nymbers between =4 up to 11, another line I say "($time < 16 and $time >=11 )" sure this will also contain <11 .

I want to have this --> 
0<$time< 4
4<$time<11
....

please...how can I manage this with php?

Link to comment
https://forums.phpfreaks.com/topic/28880-how-to-compare-variables/
Share on other sites

Change the " and " to " && " which is the operator to use.

If you want
0 < $time < 4
4 < $time < 11

What happens when $time is equal to 4?

Another way of doing the functions would be:
[code]<?php
function Greeting() {

        $time = date('G');
        $ret = 'error!';
        switch (true) {
          case ($time < 4 && $time >=0 ):
          case ($time <=23 && $time >=20 ):
                $ret = "good night";
                break;
          case ($time < 11 && $time >= 4 ):
                $ret = "good morning";
                break;
          case ($time < 16 && $time >=11 ):
                $ret = "good afternoon";
                break;
          case ($time >= 16 && $time < 20 ):
                $ret = "good evening";
                break;
          default:
                $ret = "error!";
        }
        return ($ret);
}
?>[/code]

Ken
thanks a lot ken, Im sure SWITCH will do the jub, but for now :

[code]
<?php
function Greeting() {

$time = date('G');

    if(3<$time<4) {
    return "hehe";
    }
}
?>
[/code]

will produce an error message :
Parse error: parse error, unexpected '<' in E:\xampp\eclipse\workspace\saba\data\inc.php on line 80

really how can I have something like  " 4<$i<8 " ??

thanks..

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.