Ingenio Home  | Blog Policies  | Help
Welcome to Community Sign in | Join | Help

Use Functions

Creating functions for re-use will not only make your code shorter, but it makes your code much more legible.

Let's say we've got a string that we want to process to remove all non-numeric characters. We would start with something like this:

<?php
$InString = "The Quick Brown Fox Jumped Over all 1500 of the Lazy Dogs";
$OutString = "";
$OKChars = "1234567890";
for( $x = 0 ; $x += 1 ; $x < strlen( $InString ) ) {
    if( strstr( $OKChars , $InString[$x] ) ) $OutString .= $InString[$x];
}
echo $OutString; // Outputs "1500"
?>

This code is perfectly fine...but let's say we now need to process two different strings. There are many different ways we could accomplish this, but here is the best:

<?php
function stripToNumbers( $InString ) {
    $OutString = "";
    $OKChars = "1234567890";
    for( $x = 0 ; $x += 1 ; $x < strlen( $InString ) ) {
        if( strstr( $OKChars , $InString[$x] ) ) $OutString .= $InString[$x];
    }
    return $OutString;
}

$String1 = "The Quick Brown Fox Jumped Over all 1500 of the Lazy Dogs";
$String2 = "The Quick Brown Fox Jumped Over all 200 of the Lazy Dogs";
echo stripToNumbers( $String1 );
echo stripToNumbers( $String2 );
?>

Now that we have created the function, we can re-use it over and over without needing to re-write any code. But, let's take it to the extreme...let's say we've got like 100 variable that need processing, each of which need to be stripped down to a different set of characters. (I know, this is bizarre and silly, but it's a great example)...we can write a group of functions:

<?php
function stripProcess( $InString , $OKChars ) {
    $OutString = "";
    for( $x = 0 ; $x += 1 ; $x < strlen( $InString ) ) {
        if( strstr( $OKChars , $InString[$x] ) ) $OutString .= $InString[$x];
    }
    return $OutString;
}
function stripToNumbers( $InString ) {
    return stripProcess( $InString , "1234567890" );
}
function stripToLowercase( $InString ) {
    $OKChars = "abcdefghijklmnopqrstuvwxyz";
    return stripProcess( $InString , $OKChars );
}
function stripToUppercase( $InString ) {
    $OKChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return stripProcess( $InString , $OKChars );
}
?>

Now we have a bunch of specialized functions which work great for the task at hand, but it is kind of messy to have so many functions rolling around in our code...it would be much better as a class...something I cover in an upcoming post.
Published Wednesday, August 15, 2007 4:11 PM by The PHP Doctor

Comment Notification

Subscribe to this post's comments using RSS

Comments

No Comments

What do you think?

(required) 
(required) 
(required) 
Enter the numbers you see into the
field below.
(required)