tags:

views:

129

answers:

4

Is there a better way to write the below, other then using a switch or if/else statement? Like is this a situation where a PHP's varaiable variable ( $$var ) could come to use? If so how would you write this code?

$type = 2;

switch ($type) {
 case 1:
   $type = 'gif';
   break;
 case 2:
   $type = 'jpg';
   break;
 case 3:
   $type = 'png';
   break;
 default:
   $type = 'jpg';
   break;
}
+12  A: 

I’d use an array:

$types = array(
    1 => 'gif',
    2 => 'jpg',
    3 => 'png'
);
if (isset($types[$type])) {
    $type = $types[$type];
} else {
    $type = 'jpg';
}
Gumbo
Nice so this could even be cut down to 2 lines of code right? I hate how large switch staements are especially when I need to re-use them
jasondavis
@jasondavis: Sure, you can even put everything into one line. But I prefer readability.
Gumbo
@jasondavis: Depends on how many times you hit enter :)
Zed
+7  A: 
$types = array(1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'jpg');

...

array_key_exists($type, $types) ? $types[$type] : 'jpg';
Zed
great same as above but in short version!
jasondavis
Array items are separated by commas not semocolons.
Gumbo
Thanks, fixed it.
Zed
A: 

It looks okay, however if you are using this to open a image in GD you can use a more simplified way:

ImageCreateFromString(file_get_contents('path/to/your/image.ext'));
Alix Axel
that is not what it's used for
jasondavis
+1  A: 

Since 2 is the same as the default, you could let it cascade. I like the array answers better, but if you need a switch this would be a better way to do it so you don't repeat yourself.

$type = 2;

switch ($type) {
 case 1:
   $type = 'gif';
   break;
 case 3:
   $type = 'png';
   break;
 case 2:
 default:
   $type = 'jpg';
   break;
}
nilamo
You can even leave off the `case 2:` as it is covered by `default:`.
Gumbo
Yes, of coarse. That's what I get for typing instead of thinking. Answer updated.
nilamo
I would have left it in for readability, since it clearly shows what the default is, and what value you should use for a jpg.
nickf
problem is type = 2 is always different, thats the purpose of the switch so that makes no sense
jasondavis
Ok. But from your example, the $type is 'jpg' if the number is not 1,2, or 3. 'jpg' is also what the $type is in case of 2. Since those two are the same, you can stick them together without a break so your code block only exists once.
nilamo