Scriptplayground

 Print Page | Close Window

Style Switcher

How to write a script that will allow you to easily load another stylesheet.

Here is the code to set the style

<?php
if(!empty( $_GET['theme'] ))
	{
	$style = $_GET['theme'];
	switch( $style )
		{
		case 'style1':
			$style = 'style1';
			break;            
		case 'style2':
			$style = 'style2';
			break;            
		case 'style3':
			$style = 'style3';
			break;    
		}
	}
print ""; 
?>


if(!empty( $_GET['theme'] ))
    {

This is saying if the "theme" variable is not empty than continue with the script. It reads the "theme" variable and stores the value.



$style = $_GET['theme'];

Set the value of "theme" into the "$style" variable. This can be left as a get variable, but it is easier to use a smaller, more clear variable.



switch( $style )
    {
    case 'style1':
        $style = 'style1';
        break;            
    case 'style2':
        $style = 'style2';
        break;            
    case 'style3':
        $style = 'style3';
        break;    
    }

This next piece of code is a "switch" statement. The "case" part is the string it looks for. For instance if $style had a value of "style3" than the script would load the 3rd stylesheet. The "break" says if the value of "$style" is found then jump out of the switch.



    }
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"

This is a PHP "print" or "echo". It is outputting the first part of the code to load a stylesheet into a site.



    }
" . ( ( !$style ) ? 'main' : $style ) . ".css\" />"; 

This is a tertiary operator: 1?2:3, which means "if 1 is true, then 2, else 3". This means if the "$style" variable is not filled then load "main.css". Or if it is filled, load the selected style.



That is all there is to writing a style switcher in PHP


Find this article at:
http://scriptplayground.com/tutorials/php/Style-Switcher/