PHP Switch Statement

Associate
Joined
16 Jul 2008
Posts
271
Location
London
Hi,

Normally we use the php switch statement to compare values and the isset to check if a variable is set and not null.

Is there anyway to use the switch statement to check if a variable is set.

Currently my code checks if the variable isset then runs a switch statement, can I use the switch statement to do the whole thing?

Example code:

Code:
<?php
//display either 1.video, 2.image, 3.default image
if (isset($default['swfurl'])){
echo "flash video";
} else {
	 switch ($default['imageurl']){
		 case "":
			 echo "<li>no image</li>";
			 break;						
	 default:
		 echo "<li>" . $default['imageurl'] . "</li>";								}
}
?>
 
Thanks for your swift response, seems I am using the switch statement inappropriately and will use the if else statement to achieve this as suggested.

Cheers
 
I sometimes like to use the ternary operator in place of multiple if/else/elseif statements if I think it makes the code either more compact or more readable in it's intent.

I'm not suggesting either of these reasons is true in this case just showing that it's an option. You sometimes find using the ternary operator leads to long lines of code, in which case for readability if/else statements might be the better choice.

PHP:
<?php

if (isset($default['swfurl']))
{
    echo "flash video";
} else {
    $image = !empty($default['image']) ? $default['image'] : 'No image.';
    echo "<li>$image</li>";
}

Fanstastic, amazing what you can learn from asking a simple question
 
Back
Top Bottom