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.

  1. <?php
  3. $value = 1000;
  5. // create a value like 1,000.00
  6. $currency = number_format($value, 2, '.', ',');
  8. echo $currency;
  10. ?>

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.

  1. <?php
  2. // create array
  3. $array = array('a','b','c','d');
  4. // remove an item
  5. unset($array[2]);
  6. // print out array on screen
  7. print_r($array);
  8. // now remove the offending empty array item and print
  9. print_r(array_values($array));
  10. ?>

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.

  1. <?php
  2. // create 'complex' array
  3. $array = array('a' => array('aa','ab','ac','ad'),'b','c','d');
  4. // loop through array
  5. foreach($array as $key){
  6. // is this item an array in itself?
  7. if(is_array($key)){
  8. // yes it's an array, so loop through this sub-array
  9. foreach($key as $another_key){
  10. echo '<p>'.$another_key.'</p>';
  11. }
  12. }
  13. // item isn't array, so just echo it out
  14. else{
  15. echo '<p>'.$key.'</p>';
  16. }
  18. }
  19. ?>

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):

  1. <?php
  2. // check variable exists and that it has a value
  3. if(isset($variable) && $variable != ''){
  4. echo 'do this';
  5. }
  6. ?>

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.

  1. <?php
  3. // create string
  4. $string1 = 'itchycoo';
  6. // does the first part of your string match a given value
  7. if(substr($string1, 0, 5) == 'itchy'){
  8. echo 'do this';
  9. }
  11. // does the first part of your string match a given value
  12. if(substr($string1, -3) == 'coo'){
  13. echo 'do that';
  14. }
  19. ?>

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.

  1. <?php
  4. // first array, contains all elements
  5. $array_all = array('a','b','c','d');
  6. // array 2 contians a few elements
  7. $array_some = array('b','d');
  9. // which elements present in array1 are missing from array2?
  10. $non_matches = array_diff($array_all, $array_some);
  11. // work out % of missing items
  12. $inaccuracy = round((sizeof($non_matches)/sizeof($array_all))*100);
  13. // work out % of matching items
  14. $accuracy = 100-$inaccuracy;
  16. // echo the result
  17. echo 'array2 contains '.$accuracy.'% of the content that array1 contains';
  19. ?>

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.

  1. <?php
  3. // check to see if x is greater than y
  4. if($x > $y){
  5. echo 'x is greater y';
  6. exit();
  8. }
  9. else{
  10. echo 'x is not greater y';
  11. exit();
  12. }
  14. ?>


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?

26 responses to “7 PHP functions that saved my life”

  1. 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:


  2. 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)

  3. Functions that saved my life….

    function __autoload($className)
    $className = strtolower($className);
    $classFile = “./includes/class.{$className}.php”;
    if (file_exists($classFile))
    exit(“Class {$className} not found!”);

    function print_array($array)
    $output = “”.str_replace(“\n”, “”, addslashes(ob_get_contents())).””;

    And ofcourse: glob(), array_keys(), array_key_exists and debug_backtrace()

  4. 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.

  5. 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.

  6. 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

  7. 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.

  8. @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);

  9. 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}

  10. Thanks for showing your humanness in allowing us to see ‘how it was’ without all the attitude that so often comes with php ‘professionals’.


    Btw, great contributions everyone!

  11. 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.

  12. 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’.

  13. /* 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;