Jasper
Jasper

Reputation: 2404

Is php switch statement bug?

I have a problem want to know answer, Why the following code will print A not default?

$i = 0;
switch ($i) {
    case 'A':
        echo "i equals A"; //will printed it
        break;
    case 'B':
        echo "i equals B";
        break;
    case 'C':
        echo "i equals C";
        break;
    default:
       echo "i equals other";
}

Anyone can tell me why? I truely don't understand . My PHP version is 5.2.17 Theanks.

Upvotes: 4

Views: 879

Answers (5)

Manuel Fernández
Manuel Fernández

Reputation: 483

What is happening is that (int)0 equals to (string)A.

Try changing $i = 0; to $i = '0';, it should work properly.

Upvotes: 2

Dev Jadeja
Dev Jadeja

Reputation: 130

This should work.You should convert in to string as switch case are in cases;

<?
$i = 0;
$i = (string)$i;
switch ($i) {
    case 'A':
        echo "i equals A"; //will printed it
        break;
    case 'B':
        echo "i equals B";
        break;
    case 'C':
        echo "i equals C";
        break;
    default:
       echo "i equals other";
}

?>

Upvotes: 0

LisztLi
LisztLi

Reputation: 242

try:

<?php
$i = 0;
if ($i == 'A')
{
    echo 'woo';
}

and visit this href: http://php.net/manual/en/control-structures.if.php

Upvotes: 0

Marc B
Marc B

Reputation: 360662

$i is an integer, and you're comparing to a string. PHP will typecast that string ('A') to an integer, which makes it actually be 0 as well, so yes... in PHP-land, 'A' == 0 is TRUE.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723598

This comparison is happening:

0 == 'A'

What happens is that PHP casts the string to an integer. This results in the letter A becoming zero because it doesn't represent a number.

Hence:

0 == 0

And that case meets the switch, and is therefore executed. Very counter-intuitive, but it's the way PHP's type system works, and is unfortunately technically not a bug.

You can solve this by turning $i into a string like this:

switch ((string) $i) {

Or by just initializing it as a string if you can:

$i = '0';

Upvotes: 12

Related Questions