Don’t dupe your PHP code
A common problem I see among new(er) programmers, especially to a both loosely and dynamically typed language like PHP is something I’m not exactly going to coin, but more so call “duping” or a “dupe”
Basically this is when people just assume that by aliasing or creating new variables over and over and performing multiple functions across 28 different variables then bringing them together. They could have just used a single variable and a one line solution (The Perl guys love these things, they’re called one-liners. Notorious for doing huge amounts of data manipulation and returning results in only one line of code; and no, wise guy, the “one-liner” doesn’t turn the scrollbar into a mustard seed.)
So basically it would boil down to this, lets say you wanted to get a hash using sha1() of a string, then you wanted to sha1() it again, then once more and then return a little “key” with a set string length (For whatever reason, cool, but it’s just an example for right now.)
The code might look something like this:
// return a string’s hash
function three_hash($str) {
// hash the string
$hash = sha1($str);
$hash = sha1($hash);
$hash = sha1($hash);// split the key
$key = substr($hash, 0, 10);// return the hashed split key
return ($key);
}
Now the majority of you say “Wow, that’s dumb…who would do that?” Well surprisingly a huge amount of progammers (including some of my old code I look through, you know it’s bad when you wrote it and you look at it and say to your self “What in the world is this guy doing?” then you realize it’s yours. So to help some new-comers to the programming world, I’m writing this.
The code above could have just as easily been this:
// return a strings hash footprint
function three_hash($str) {
return (substr(sha1(sha1(sha1($str)))), 0, 10));
}
Granted, it might not be as “pretty” but to me it is. Just something to keep in mind when you’re making functions, or just writing little scripts. Even though this was an extreme example, it still applies to just about anything. The more corners you cut and the more variables you eliminate the less processing PHP has to do and the more you can be on your way to speeding up your codes run-time considerably.
Just a thought.
-bryan
