Number comparison: Greater than x but less than y... how?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mattcooper
Forum Contributor
Posts: 210
Joined: Thu Mar 17, 2005 5:51 am
Location: London, UK

Number comparison: Greater than x but less than y... how?

Post by mattcooper »

Hi guys,

I'm trying to write a simple game and need to create outcomes that depend on the value of $var.

If $var is between 100 & 110, event #1 happens;
If $var is between 111 & 120, event #2 happens;

etc...

Does anyone know a way of doing this with a switch() statement? If not, another simple way?

Thanks in advance!

Matt
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

if they fall into even buckets (say the 10 blocks you've posted) .. floor($var/10)

For forcing a value to a given range, I use

Code: Select all

$value = min(max($value, $low), $high);
User avatar
mattcooper
Forum Contributor
Posts: 210
Joined: Thu Mar 17, 2005 5:51 am
Location: London, UK

Post by mattcooper »

many thanks again, Feyd, floor() works nicely for me... and is easy to work into a switch statement.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

If they are uneven or irregular categories/buckets, you can do something like:

Code: Select all

<?php

switch (true) {
    case (($value > 0) && ($value < 10)):
    //do something
    break;

//etc..

}

?>
Though it is messy and I personally would try not to use it.
Post Reply