7 PHP functions that saved my life
From time to time, I’ve struggled with minor pieces of coding for what seems like an age and then I’ve discovered PHP has a ready-made function whose express purpose seems to be to fix my exact problem. Today, I name and honour those PHP functions which saved my life, my career and my sanity.
1. number_format
Having spent an age, trying to work out if a number I’d just rounded up (using round()) to be used as a price had a trailing zero or not, I discovered number_format(). If you need a number value to look like a currency and always have 2 decimals places then round() won’t cut it but number_format() will.
<?php$value = 1000;// create a value like 1,000.00$currency = number_format($value, 2, '.', ',');echo $currency;?>
2. array_values
Recently, I needed to loop through an array and remove the occasional value (using unset($array[n])) but the resulting array now had empty values in it - so in-stepped array_values(). array_values takes an array (preferably not an indexed array as this function doesn’t preserve indexes) and reorders it.
<?php// create array$array = array('a','b','c','d');// remove an itemunset($array[2]);// print out array on screenprint_r($array);// now remove the offending empty array item and printprint_r(array_values($array));?>
3. foreach()
One of my first projects, as a proper web developer (at an agency) was to do the HTML/CSS integration for a new website where an outside programmer had done all the (OO) PHP. THe developer’s data was all stored in multi-dimensional arrays (which I’d hardly ever worked with) and I was having a nightmare getting the data out until I discovered foreach(). No matter what array I throw at it, it’ll always get through it and give me the results I need. It’s my favourite loop by far… in fact it’s pretty much the only loop I ever use.
<?php// create 'complex' array$array = array('a' => array('aa','ab','ac','ad'),'b','c','d');// loop through arrayforeach($array as $key){// is this item an array in itself?if(is_array($key)){// yes it's an array, so loop through this sub-arrayforeach($key as $another_key){echo '<p>'.$another_key.'</p>';}}// item isn't array, so just echo it outelse{echo '<p>'.$key.'</p>';}}?>
4. isset()
Most LAMP server environments allow you to simply test like this; if($variable) { echo 'do this'; } but, a lot of (LAMP) servers will throw an error so it’s always best to be safe and to do this (or similar):
<?php// check variable exists and that it has a valueif(isset($variable) && $variable != ''){echo 'do this';}?>
5. substr()
I seem to always fall back on substr(). It’s so easy to find out if the first or last x characters in the string equal another given string and off you go.
<?php// create string$string1 = 'itchycoo';// does the first part of your string match a given valueif(substr($string1, 0, 5) == 'itchy'){echo 'do this';}// does the first part of your string match a given valueif(substr($string1, -3) == 'coo'){echo 'do that';}?>
Yes, there are probably better ways to do this - preg_match() or similar but…
6. array_diff()
array_diff() is one of those functions, I’ve only used once (so far) but it did save my sanity at the time. I was looking for a way to get a percentage difference between two different arrays - so I could say how closely they matched each other and before discovering array_diff() I struggled for days no knowing how to do it.
<?php// first array, contains all elements$array_all = array('a','b','c','d');// array 2 contians a few elements$array_some = array('b','d');// which elements present in array1 are missing from array2?$non_matches = array_diff($array_all, $array_some);// work out % of missing items$inaccuracy = round((sizeof($non_matches)/sizeof($array_all))*100);// work out % of matching items$accuracy = 100-$inaccuracy;// echo the resultecho 'array2 contains '.$accuracy.'% of the content that array1 contains';?>
7. exit()
exit is a godsend. If your code (or more likely someone else’s code) is causing errors but you don’t know where - you can put an exit(); or just exit; after something significant is supposed to happen to see if it has. If you precede the exit statement with an a meaningful echo you’ll know exactly where the code has/hasn’t stopped. THis one function has made my debugging skills a million times stronger.
<?php// check to see if x is greater than yif($x > $y){echo 'x is greater y';exit();}else{echo 'x is not greater y';exit();}?>
Summary
These days, I find myself in less and less situations where a PHP function saves my life - mainly because as I’ve got more experienced in web development I’ve learnt how to read and search through the PHP manual more efficiently. The memories, of when I tried to do things the long way for days or weeks before stumbling across a PHP function that did what I wanted to do but so much easier, are fading now.
Please feel free to comment, criticise, deride and improve my code examples - I don’t profess to be the world’s number 1 PHP programmer so I welcome any information that may help me and this website’s readership.
Have any PHP functions saved your life?
Like this article?
Why not subscribe to the <img /> is Everything RSS updates feed?
January 18th, 2008 at 12:50 pm
You know you can combine the echo and the exit() call:
exit(”x is greater than y”);
When debugging forms, I find it very handy to write a little helper function that spits out the contents of the $_POST array wrapped in PRE tags, then call that:
die(post_contents());
January 18th, 2008 at 2:31 pm
No I did not know that about the exit(); That’s great!
I have my own function like your post_contents() that does a similar job - that I call niceError() - which prints out any array or string given to it in a nice and pretty way (hence the way)
January 18th, 2008 at 11:55 pm
Functions that saved my life….
function __autoload($className)
{
$className = strtolower($className);
$classFile = “./includes/class.{$className}.php”;
if (file_exists($classFile))
{
include($classFile);
}
else
{
exit(”Class {$className} not found!”);
}
}
function print_array($array)
{
ob_start();
print_r($array);
$output = “”.str_replace(”\n”, “”, addslashes(ob_get_contents())).”";
ob_end_clean();
return($output);
}
And ofcourse: glob(), array_keys(), array_key_exists and debug_backtrace()
January 19th, 2008 at 11:35 am
Thanks for the input SchizoDuckie. A former colleague of mine used to use __autoload() and had great success with it - maybe I should give it a try.
January 19th, 2008 at 8:03 pm
switching to python from php was how i really saved my life. Try that language and its frameworks, don’t die on php! :P
January 20th, 2008 at 7:37 am
Technically speaking, foreach() isset() and exit() are language constructs. :)
print_r() is a life saver for debugging code. wrap that in some pre tags and it makes life much easier. I tend to not have to do that part so much now that I develop through unit tests these days, since I very rarely am looking at browser output when working inside of class methods.
January 20th, 2008 at 2:03 pm
number_format looks cool, not used that before. one cool thing I recently discovered about foreach is you can use it to emulate for($i = 0;$i
January 20th, 2008 at 6:18 pm
Some more help…
1. If you dont already use a framework get the Zend Framework.
2. Use sprintf for future internationalization:
public function __tostring() { return sprintf(_(’Contact: %1$s, %2$s, %3$s. Message: %4$s’), $this->name, $this->phoneNumber, $this->emailAddress, $this->message); }
Dont split up an english sentence to put a link or button in between an expect the 2 halves of the sentence to be meaningfull in other languages or the button/link placement to be the same in all languages.
3. Always use the php filters on input: http://no2.php.net/manual/en/ref.filter.php
4. Use class constants defined at the top of the class instead of comparing numbers/text for settings in methods/input. Makes it easier to change a setting in the future without digging through many files.
January 21st, 2008 at 11:33 am
// instead of this:
if(isset($variable) && $variable != ”){}
// you can do this:
if(!empty($variable)){}
// it’s the same
January 22nd, 2008 at 3:01 pm
Phil Thompson’s Blog: 7 PHP functions that saved my life…
On his blog, Phil Thompson lists seven PHP functions that “saved ……
January 22nd, 2008 at 4:04 pm
@SchizoDuckie:
ob_get_clean() saves you the ob_end_clean() call.
But if you just want a modified print_r() output, why don’t you use the second parameter so you don’t need ob_*() anymore:
print_r($array, true);
January 22nd, 2008 at 4:12 pm
[…] his blog, Phil Thompson lists seven PHP functions that “saved his life” when developing his apps: From time to time, I’ve […]
January 22nd, 2008 at 5:24 pm
debug_backtrace() is also rather useful for debugging.
Or throwing and catching exceptions as well.
January 22nd, 2008 at 6:02 pm
Here’s another tip: The need for substr() is often not needed if you only need the first or the nth character, you can use the curly-braces syntax in those situations:
For example: substr($var, 0, 1) is the same as $var{0}
January 22nd, 2008 at 6:04 pm
There are some great tips coming in from different people in these comments.
Keep them coming.
January 22nd, 2008 at 8:52 pm
When checking for elements in arrays, array_key_exists() is generally better than isset().
Regards,
Rob…
January 22nd, 2008 at 11:24 pm
Thanks for showing your humanness in allowing us to see ‘how it was’ without all the attitude that so often comes with php ‘professionals’.
Steve
Btw, great contributions everyone!
January 23rd, 2008 at 3:34 am
Posts like this one, seem to get back to remind us that you can always improve your code by going back to what is already there, but was long forgotten. Nice ;)
January 23rd, 2008 at 10:19 am
If you like number_format(), then you’ll LOVE PECL/intl’s NumberFormatter class. All the ease of number_format() with all the localized knowledge of the International Components for Unicode.
http://docs.php.net/manual/en/class.numberformatter.php
January 23rd, 2008 at 3:41 pm
This is really helpful for me:
print “”. print_r(get_defined_vars(),true) . “”;
Prints all defined variables on php run.
January 23rd, 2008 at 4:13 pm
well, there’s a <pre> tag inside the “”
January 24th, 2008 at 11:38 am
As noted in the comments, foreach is a language construct, and certainly isn’t just a PHP thing. Isset and exit (also die) are a little dubious, although they are technically language constructs, even though they behave just like any normal function.
January 24th, 2008 at 11:42 am
Thanks Draicone but, this post might have lost some of its edge had it been entitled ‘7 PHP functions, language constructs, general idealisms, and working practices that saved my life’.
February 22nd, 2008 at 9:49 pm
/* I used to be afraid of arrays especially storing form post data into arrays. I whipped up the following fun(ction) to convert my crappy custom strings “arrays” into true arrays.
I would store something like ‘eat~more~cheese~please’ in my database.
*/
$string = unzip($string,’~');
echo $string[0]; // eat
echo $string[2]; // more
echo $string[3]; // cheese
echo $string[4]; // please
// function below
function unzip($string,$div) {
$count = 0;
$lengthdiv = strlen($div);
if(substr($string, -strlen($div)) != $div) { $string .= $div;}
while (strpos($string,$div)!=null) {
$break = strpos($string,$div);
$unzip[$count] = substr($string, 0, $break);
$string = substr($string, $break+$lengthdiv);
$count += 1;
if($break==strlen($string)){ $unzip[$count] = $string; }
}
return $unzip;
}
March 23rd, 2008 at 5:18 pm
i think these are too primitive functions.
March 23rd, 2008 at 5:31 pm
Alex: too primitive for what? to be useful?