Drewdin
Drewdin

Reputation: 1762

switch statement will not equate zero?

I have the following function that works properly, except for when you use the input value of 0. I tried searching around to see if the 0 is equated as a NULL or if I'm doing something wrong.

When a zero is input, it outputs advanced which is greater than 20. Can anyone explain? Thanks

I plan on making the switch equate 0-10, 11-20, 21-30, 31-40, 41+ but for this example i am just using two scenarios. Thanks

**EDIT I do want values when its 20 :)

function strengthPlan( $data ) {

    $data = ( int ) $data;
    switch( $data ) {
        case( $data <= 19 ):
            $result = 'standard strength';
            break;
        case( $data >= 20 ):
            $result = 'advanced strength';
            break;
    }
    return $result;

}

echo strengthPlan( 0 );

Upvotes: 1

Views: 419

Answers (3)

Jonah
Jonah

Reputation: 10091

That's not how switch statements. They compare the case to the value you provide to switch. Here's what you should do instead:

function strengthPlan($length) {
    return $length >= 20 ? 'advanced strength' : 'standard strength';
}

If you're planning on using more conditions, then use an if...elseif statement as follows:

function strengthPlan($length) {
    if     ($length <  5) return 'micro strength';
    elseif ($length < 10) return 'tiny strength';
    elseif ($length < 15) return 'small strength';
    elseif ($length < 20) return 'standard strength';
    elseif ($length < 30) return 'advanced strength';
    else                  return 'super strength!!!!!';
}

It will trickle down each condition until it hits a number that it is within. Alternatively, you can use sort of a lookup table style like this:

function strengthPlan($length) {
    $plans = array(
        1            => 'super strength!!!!!',
        $length < 30 => 'advanced strength',
        $length < 20 => 'standard strength',
        $length < 15 => 'small strength',
        $length < 10 => 'tiny strength',
        $length < 5  => 'micro strength',
    );
    return $plans[1];
}

There was a discussion about this here: http://forums.devnetwork.net/viewtopic.php?f=50&t=113253

Upvotes: 4

genesis
genesis

Reputation: 50976

Using switch in this case is wrong

Use this one

http://sandbox.phpcode.eu/g/b4053.php

<?php 
function strengthPlan( $data ) { 
    return ($data > 20) ? 'advanced strenght' : 'standard strenght'; 
} 

echo strengthPlan( 0 );

Upvotes: 0

pimvdb
pimvdb

Reputation: 154858

Your logic is incorrect. Switch statements are checking for equality. Your code is checking whether $data is equal to TRUE or FALSE.

 case( $data < 20 ):

will evaluate to:

 case( TRUE ):

because 0 < 20.

Since 0 is not equal to TRUE but to FALSE (after conversion), the second case is run.

Basically, you cannot use switch case for < or > but only for ==.

Upvotes: 12

Related Questions