你会怎么做这个PHP代码?

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;
}
$types = array(1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'jpg');

...

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

I’d use an array:

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

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

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