Jump to content

help with switch statement and multiple variables


stickynote427

Recommended Posts

I'm trying to create a rudimentary theme-selection page on my site, for future use. I have a small form that allows you to change the background color of the page; your selection is saved in a cookie so that the color is still applied when the page is visited later.

 

I also want text colors that I define to go along with each background color, which the visitor chooses. However, I'm having a problem. Here is the code I have:

 

<?php

switch($_COOKIE["theme"]) {
case 'red': $color="green"; $themeType="color"; break;
case 'green': $color="red"; $themeType="color"; break;
case 'blue': $color="orange"; $themeType="color"; break;
case 'purple': $color="yellow"; $themeType="color"; break;
case 'black': $color="white"; $themeType="color"; break;

?>

 

But I think it is redundant and unnecessary to repeat $themeType="color"; over and over again, and it would be a bit of a nuisance to have to add in if I wanted to add more colors later. I tried fixing this by using something like this:

 

<?php

switch($_COOKIE["theme"]) {
case 'red': $color="green";
case 'green': $color="red";
case 'blue': $color="orange";
case 'purple': $color="yellow";
case 'black': $color="white";
$themeType="color"; break;
}

?>

 

But that does not work.

 

Here is basically want I want my PHP code to do: if the cookie has a value of red, set $color to green; if it has a value of green, set $color to red, and so on. Then, no matter what the cookie's value is, set $themeType to color.

 

Any ideas?

 

Thanks.

stickynote427

Agh, sorry. I think I have solved the problem. Here is my new code:

 

<?php

$themeArray=array(
'red',
'green',
'blue',
'purple',
'black');

$colorArray=array(
'green',
'red',
'orange',
'yellow',
'white');

if (in_array($_COOKIE["theme"],$themeArray)) {
$color=$colorArray[array_search($_COOKIE["theme"],$themeArray)];
$themeType="color";
}

?>

 

The code first sets a theme array with the background colors, and then a color array with the corresponding font colors. It then checks to see if the value of the theme cookie is in the theme array, and if it is, find the key of the background color in the array, and set $color to the value in the color array that has the corresponding key.

 

I'm sure that sounded confusing, but my code seems to work now. I apologize for any inconvenience.

 

Thanks.

stickynote427

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.