Post a job. Find one. authenticjobs.com

Advertisement

Partially Functional

Posted on Wednesday, September 30th, 2009 at 11:22 pm

PHP functions can be extremely useful if you have a chunk of code that you plan on using multiple times in your scripts. Functions keep everything all neat and tidy and in the case you have to make a change, you only have to edit one place instead of multiple places.

Enough theory, lets get our hands dirty.

Lets say you have a long list of navigation items and you want to show which navigation item is currently active. Surprise, we are going to make that happen. Lucky!

First we start with our navigation items.



OK, so we’ve got our list of navigation items. To show the user that the link is active we are going to apply a class of “active” on our li. Instead of writing an if statement for each list item, we are going to write a function that checks if the current list item is the one we want active.

We start buy create a variable and a blank function in php as well as passing 2 variables along with the function.

$area = 'apples';

//create the function
//we are going to be passing 2 variables into the function
function make_active($current_area,$link_area){

}

The 2 variables we are going to pass is $current_area, which is going to tell the function which area we are on, and $link_area, which tells the function which link we want to check.

So, basically inside our function we want to check if the 2 variables are equal to each other, and if they are we are going to return some html.

//inside our function
if($current_area == $link_area){
       return ' class="active"';
}

Our function is now checking to see if $current_area is equal to $link_area and if it is we are returning a class tag. Now that we have our function created, we need to reference it in each of our links.


You’ll notice that inside each li we are echoing out the results of our function. The first argument of our function is the $area variable (which is currently set to apples) and the second is the name of our link. If you run this script and view the source we should see that the first li now has a class of “active” and all the other li’s have no class.

If you edit the area variable above our function you can see that each link changes if the area is set to active.

That is the most basic function I can think of that I use on a daily basis. It’s doesn’t seem like much, but cuts down on our overall lines of code ten fold.

If you’ve never worked with functions you should now have a basic idea of what they are and how the work. For more information on functions you can read up on them on php.net.

You can also download the source code of this quick tip!

Share these links, you kinda have to!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Twitter