Page 1 of 1

$number = 1,3,5,6,8,9

Posted: Fri Jul 21, 2006 2:51 pm
by tecktalkcm0391
Is there a way to write out an if statement where $numbers= any of these numbers 1 2 4 5 6 8 9 with out having to do $numbers=1 || $numbers=2 ...

Posted: Fri Jul 21, 2006 3:03 pm
by feyd

Posted: Fri Jul 21, 2006 3:04 pm
by Ward
If you're just trying to find if a value is numeric, you can use:

Code: Select all

if (is_numeric($numbers))
However if you're trying to find if a value is numeric AND beween 0 and 9, then

Code: Select all

if (is_numeric($numbers) && $numbers >=0 && $numbers <= 9)

Posted: Fri Jul 21, 2006 3:13 pm
by daedalus__

Re: $number = 1,3,5,6,8,9

Posted: Fri Jul 21, 2006 3:34 pm
by jmut
tecktalkcm0391 wrote:Is there a way to write out an if statement where $numbers= any of these numbers 1 2 4 5 6 8 9 with out having to do $numbers=1 || $numbers=2 ...

Code: Select all

$number = 1;
switch ($number) {
	case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
            echo $number;
		break;

	default:
	    echo 'not one of the numbers';
		break;
}


in_array()  is most appropriate though

Posted: Fri Jul 21, 2006 4:20 pm
by feyd
regular expressions are overkill in this case I would say.

Posted: Fri Jul 21, 2006 4:42 pm
by MrPotatoes
so would be doing a math equation to figure it out. just do the switch statement like above

Posted: Fri Jul 21, 2006 4:58 pm
by Ward
The switch is overkill, when you can do it in one line with my method. Since PHP doesnt have strong data types, you actually don't even need the is_numeric part, this would actually work:

Code: Select all

if ($number >=0 && $number <= 9)

Posted: Fri Jul 21, 2006 5:15 pm
by Benjamin
Ward wrote:The switch is overkill, when you can do it in one line with my method. Since PHP doesnt have strong data types, you actually don't even need the is_numeric part, this would actually work:

Code: Select all

if ($number >=0 && $number <= 9)
Your code would return true for the numbers 3 and 7.

Posted: Fri Jul 21, 2006 5:25 pm
by Luke

Code: Select all

<?php
$num = 5;
$array = array(1, 2, 4, 5, 6, 8, 9 );
if(in_array($num, $array)) echo $num  . " is one of the numbers";
?>

Posted: Fri Jul 21, 2006 5:40 pm
by Ward
astions wrote:
Ward wrote:The switch is overkill, when you can do it in one line with my method. Since PHP doesnt have strong data types, you actually don't even need the is_numeric part, this would actually work:

Code: Select all

if ($number >=0 && $number <= 9)
Your code would return true for the numbers 3 and 7.
Yeah, I didnt notice that 3 and 7 weren't included in the matches. My bad, I misread. Thats what running on 4 hours of sleep a night will do to you :P