Greater/Lesser than a Numeral (PHP Switch)

Why does the switch below give me an “unexpected ‘>’” error? I Google’d for examples and found some that write it case > $numeral and others that write it case > = $numeral, but both give me the same error.

I want to display a centered image ($Img1C) if that image is more than 250 pixels wide, with the default image size floated to the right ($Img1R).

Thanks.


switch($Width1)
{
 case > 250:
 $Img1st = $Img1C;
 break;
 default:
 $Img1st = $Img1R;
 break;
}

i’m not sure where you saw those samples, but they must not have been php. here’s the supported syntax of switch: http://us2.php.net/manual/en/control-structures.switch.php

Thanks, but there’s only one mention of a greater than/lesser than value on that page…


<?php
switch ($i) {
case 0:
case 1:
case 2:
    echo "i is less than 3 but not negative";
    break;
case 3:
    echo "i is 3";
}
?>

I tried a lame experiment to change it to a switch that says “anything less than 250”…


switch ($Width1)
{
 case 0-249:
 echo "Width is less than 250";
 break;

 default:
 echo 'DEFAULT';
 break;
}

But it doesn’t work.

The Manual has a page of “Comparison Operators,” with $a > $b apparently working with IF functions. Is there a way to adapt this to a PHP switch?

Thanks.

AFAIK, this can’t be done in a PHP switch. You can use if/else statements, and if you want slightly cleaner syntax, try the alternative syntax (e.g. if(statement): … endif; ). The switch structure is only for easily executing code based on known values of a statement/variable.

Thanks.

This can be done 1 sec


<?php

switch (true) { # Pay close attention to the true.
    case $Width1 > 250: # if true, enter; if false, skips;
        $Img1st = $Img1C;
    break;
    
    default:
        $Img1st = $Img1R;
    break;
}

It can, but we shouldn’t encourage geosite to continue this pseudo-language he is creating where switch() trees control all program flow whether appropriate or not.

//3 lines with if()
$Img1st = $Img1R;
if ($Width1 > 250)
  $Img1st = $Img1C;

//1 line with ternary operator
$Img1st = ($Width1 > 250) ? $Img1C : $Img1R;

Thanks for the elegant solution, Dan.