totallyuneekname
totallyuneekname

Reputation: 2020

Best way to check what a variable is

I was wondering what the quickest way would be to do something like the following:

if ($var == 1) {
// 1
}
if ($var == 2) {
// 2
}
if ($var == 3) {
// 3
}

etc, but then at the end having something like:

if ($var != 1 or 2 or 3) {
//Not a number
}

I was thinking about having an if(in_array(...)) statement at the end, but wanted to know your thoughts.

Upvotes: 0

Views: 67

Answers (4)

phant0m
phant0m

Reputation: 16905

Use if/else if/else, with which you can decide whether strict or loose comparisons are appropriate.

With switch, it's always loose comparisons, which is why I prefer the if statement, since it makes it explicit what mode has been chosen.

if ($var === 1) {
// 1
}
else if ($var === 2) {
// 2
}
else if ($var === 3) {
// 3
}
else {
//neither 1, 2 nor 3
}

Upvotes: 0

Mamuz
Mamuz

Reputation: 1730

Or use a switch case, this better to read for much cases:

switch($var) {
    case 1: /*1*/ break;
    case 2: /*2*/ break;
    case 3: /*3*/ break;
    default: /*not 1 not 2 not 3*/
}

Upvotes: 1

paulsm4
paulsm4

Reputation: 121881

If all you want to know is whether "$var" is in your set {1, 2, 3}, then in_array is fine.

Otherwise, if you want to know which (if any) value you've got, then I'd do this:

if ($var == 1) {
// 1
}
else if ($var == 2) {
// 2
}
else if ($var == 3) {
// 3
}
else {
}

Note the "else if" to save you from re-checking what you already know.

Note, too, that PHP 4 and 5 also have a "switch" case/block:

switch ($i) {
    case 1:
         // 1
        break;
    case 2:
         // 2
        break;
    case 3:
         // 3
        break;
    default:
        ...
}

Upvotes: 1

Coin_op
Coin_op

Reputation: 10728

I would do this with a switch

switch ($var) {
    case 0:
        echo "var equals 0";
        break;
    case 1:
        echo "var equals 1";
        break;
    case 2:
        echo "var equals 2";
        break;
    default:
       echo "var is not 0 1 or 2"
}

Also if you miss out a break statement then you can easily do a case when $var == 1 || $var == 2, read more

Upvotes: 6

Related Questions