JasonDavis
JasonDavis

Reputation: 48933

How would you do this php code?

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;
}

Upvotes: 1

Views: 167

Answers (4)

nilamo
nilamo

Reputation: 1942

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;
}

Upvotes: 1

Zed
Zed

Reputation: 57648

$types = array(1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'jpg');

...

array_key_exists($type, $types) ? $types[$type] : 'jpg';

Upvotes: 7

Alix Axel
Alix Axel

Reputation: 154533

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'));

Upvotes: 0

Gumbo
Gumbo

Reputation: 655219

I’d use an array:

$types = array(
    1 => 'gif',
    2 => 'jpg',
    3 => 'png'
);
if (isset($types[$type])) {
    $type = $types[$type];
} else {
    $type = 'jpg';
}

Upvotes: 12

Related Questions