Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

SWITCH returns TRUE when comparing letters to numbers. WHY?

Short question: WHY?!?

The below class returns ALL ALLRIGHT when calling:Status::validate('ab')

class Status
{
    const FRESH = 0;
    const PENDING = 25;
    const CANCELLED = 50;

    public static function validate($status)
    {
        switch ($status) {
            case self::FRESH:
            case self::PENDING:
            case self::CANCELLED:
                echo 'ALL ALLRIGHT';
            default:
                echo 'ERROR!';
        }
        die;
    }
}

Upvotes: 1

Views: 67

Answers (1)

Forien
Forien

Reputation: 2763

I believe it's because your $status is being casted to int.

$value = 'abc';
$other_value = '21abc';

echo (int)$value;
echo '<br>';
echo (int)$other_value;

Will return:

0
21

And that would cause it to think that ab value is equal to Status::FRESH

I'm not sure though if switch statement does this type of typecasting.

Edit

And I think I was right. More info here PHP Manual - switch.
Reference on typecasting strings to integers here PHP Manual - Strings.

Upvotes: 4

Related Questions