Category Archives: Uncategorized

Refactoring in Practice

I love taking larger functions and slimming them down into a more efficient and readable format. Here is a simple example of just that.

The original function:

function strip_slashes( $data )
{
    if( is_array($data) )
    {
        foreach($data as $key => $val )
        {
            $data[$key] = strip_slashes($val);
        }
    }
    else
    {
        return stripslashes($data);
    }

    return $data;
}

The refactored function:

function strip_slashes( $data )
{
    return is_array($data) ? array_map('strip_slashes', $data) : stripslashes($data);
}

The code is much more readable and can be understood easily. Try to do the same with your own functions. The more you practice refactoring old code the easier it will be to remember how to do things quicker.

Don’t Hard Code Your Age!

Even though this is not at all as important as not hardcoding copyright years. It can still a time saver if you happen to hard code your age into a biography on a website.

Lets make those ages DYNAMIC!

I wrote a little code snippet which updates your age automatically. All you do is enter your birth date and php does the rest! I will use my birthday in the example:

$birth_date = getdate(strtotime("August 1st 1988")); $current_date = getdate(time()); echo ($current_date['mday'] >= $birth_date['mday'] AND $current_date['mmonth'] >= $birth_date['mmonth']) ? ($current_date['year'] - $birth_date['year']) : (($current_date['year'] - $birth_date['year']) - 1);

This would return 21, which is how old I am currently. If the current time was July 31st 2009, it would return 20. I made sure it checked both the day and month, not just subtract the years, to figure out the date. Just replace “August 1st 1988″ with your birth date.

It’s that Simple.