Quick Tip: 7 Super-Handy PHP Functions for Beginners

Quick Tip: 7 Super-Handy PHP Functions for Beginners

Tutorial Details
  • Topic: PHP
  • Difficulty: Beginner
  • Estimated Completion Time: 20 min

Have you ever taken a look at the list of functions available in PHP? I just counted 5025 on the PHP quick reference page. Granted, it depends on what extensions you have enabled, but still: that’s one heap of functions! While I can’t show you every one of them, if you’re new to the language, I’ll introduce you to seven really handy ones in this quick tip!


Function 1: array_rand

Let’s start with a simple one. Ever want to get a random item out of an array? You might use rand or mt_rand to get a random number, passing 0 and the last index of the array as the min and max parameters; this will give you a random key that you can use to pull a value from your array.

However, there’s a way that’s a little bit quicker: array_rand. Just pass it your array, and it will return the random key.

$sites = ["Nettuts+", "Psdtuts+", "Mobiletuts+", "Mactuts+"];
$k = array_rand($sites);
$sites[$k];

If you want more than one random value from the array, pass a second parameter identifying how many; you’ll get back an array of random keys.


Function 2: strip_tags

It’s not uncommon to accept larger chunks of text from a user: maybe as a comment or a bio. Of course, you probably don’t want just any HTML tags to be allowed in that text, though, right? You don’t want random JavaScript running, or perhaps your styling dictates they only use plain text. So, you’ll want to strip out the HTML tags they enter, using strip_tags:

$message = "<div> This is my bio </div>";
echo strip_tags($message); // "This is my bio"

Of course, you might want to allow certain tags, like <strong>, <em>, or <code>, for some simple styling; pass a string listing those as the second parameter:

$message = "<div> This is <strong>my</strong> bio </div>";
echo strip_tags($message, "<strong><em><code>"); // "This is <strong>my</strong> bio"

Function 3: strftime

Dates are a big part of any web apps, so you should be able to output them in any format you need. It’s not hard to get a timestamp—you’ll pull it from a database or use time(), maybe—but how about formatting it? The strftime function can format that timestamp in any way you’d like. You’ll pass it a format string and the timestamp and get the date back out.

strftime("%B %d, %Y", time()); // July 28, 2012

Of course, it’s impossible to memorize all the formatting tokens, so I use the handy strfti.me to help me; give it a try, and you’ll love it, too.


Function 4: basename

When working with a file, you usually want to get at it via its absolute path. However, if you need to display information about this file to the user, you probably just want to show them the file name, and not its whole path. Enter basename: this handy function will strip that path down to just the file name; just pass it the path as the parameter; if you want to get rid of a suffix, like a file extension, pass that suffix as the second parameter.

$path = "/some/long/path/to/the/special_file.txt";
$filename1 = basename($path); // special_file.txt
$filename2 = basename($path, ".txt"); // special_file

Function 5: list

This one’s pretty cool: let’s say you have an array, and you want to assign its items to variables of their own. The list function makes this super-simple:

$array = ["Ellery", "Queen"];
list($first_name, $last_name) = $array;

echo $first_name; // Ellery
echo $last_name; // Queen

As you can see, we just pass the new variable names as parameters to the list function and set that equal to the array. It’s a bit different from the normal syntax, since the function call is on the left, but, yes, it does work. Here’s a good example from the PHP docs (for explode):

$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);

Function 6: range

If you ever need a list of numbers to iterate over, you’ll want to check out the range function. Just pass it a starting and ending number (or letter), and it will return an array of the numbers:

range(0, 10); // array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
range('a', 'f'); // array('a', 'b', 'c', 'd', 'e'. 'f');

As you can see, it’s an inclusive range, so both the numbers you define are included. You could also pass a step parameter to specify the increment between numbers:

range(2, 10, 2); // array(2, 4, 6, 8, 10);

Function 7: isset

Here’s a handy way to check if a variable has been set: use the isset function. You just pass it a variable name, and it will return true if that variable exists, and is set to something other than NULL.

$name = "Joe";

isset($name); // true
isset($age); // false

Since this function also works with the items in array and associative arrays, this function is often used to check for the existence of specific keys on the $_GET and $_POST superglobal arrays: if a given value exists, you’ll do one thing; otherwise, you’ll do something else. For example, a search page might go something like this:

if(isset($_GET['query'])) {
    // get results and display them
} else {
    // show some default content
}

New to PHP?

I’ve written a new ebook, Getting Good with PHP, with Rockable Press.

Well, there you go: seven handy PHP functions you should find pretty useful as you code. If you’re new to PHP, I want to let you in on something: I’ve written a new ebook, Getting Good with PHP, with Rockable Press. I wrote it especially for those who don’t know a thing about PHP, but want to get up to speed as quickly as possible. If that’s you, I hope you’ll check it out when it releases in the extremely near future! We’ll keep you posted.

So, now that you’ve read my choices, what do you think PHP’s most handy function are? Let us know in the comments!

Tags: tips
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • spawnius

    And a lot more handy stuff can be found on php.net :D

  • http://www.lukespoor.com Luke S

    This is great for newbies like myself! And I also can’t wait for the eBook! Any ideas when it’ll be available?

    • http://rockablepress.com Naysan

      Hi Luke,

      Andrew’s book called ‘Getting Good with PHP’ is going to be released sometime this week!

      You can download the first 15 pages of his book here: http://bit.ly/MyOt75

      Thanks for your support!

  • http://brianswebdesign.com Temecula

    I’ve never used strftime(), and actually never seen it used either. I use date(). I’ve managed to memorize a few of the date formatting characters. Why did you choose strftime over date?

    • http://edmundask.lt Edmundas

      strftime() allows to have localized date and time formats (you can set locale options through setlocale()). date() function, on the other hand, ignores locale settings. It is explained in more detail on php.net.

    • http://en.funivan.com funivan

      For example is is simple to get difference between dates, and is it simple to manage format of date.

  • briedis

    Why use strftime() not date()?

    • http://github.com/gorelative Mike

      More importantly, why use date() and not DateTime->Format()? Proper use is $date = new DateTime(123123124124124); $date->format(“d/m/Y”);

      • Abhijit

        Agreed, DateTime is the best option.

      • http://www.step4wd.com M. Ahmad Zafar

        Isn’t date() the conventional and DateTime() the Object Oriented approach of the same thing?

      • http://www.wimbledon-it.co.uk Richard

        Yes, and dont forget to mention “DateInterval” since PHP 5.3.0 which is pretty useful for intervals like adding 30minutes to a list of times from 9 to 5 for a select box!

      • http://www.xpertdeveloper.com Avinash
  • Mark L

    I don’t believe I’ve ever used strftime() before. So I was curious if I’ve been doing things backward all this time using date() to format my time stamps. Turns out, date() is a lot more cross-platform friendly. The doc for strftime() has a few caveats.

    I ran a quick test and it turns out that date() is cheaper on ram usage at ~280 bytes per call versus strftime()’s ~640 bytes while being only marginally slower by about 0.00013 seconds on average.

    I personally prefer the formatting of date(). It just seems cleaner IMO. It is nice to know that there are options. I suppose it comes down to preference at this point.

  • Francisc

    date() has a few bugs and doesn’t support locale.
    strftime() is preferred to date().

    • https://github.com/gorelative Mike DeVita

      Also, date() will quit working i think around 2030.. Best to use DateTime() like i mentioned above.

  • http://leorothe.com Leonardo

    Correction: list and isset are not functions, but language constructs. As such, they are limited in the kind of tokens and expressions you can use on them. Don’t be fooled by the function-like syntax (think of the sizeof operator in C).

    • David D’hont

      Still, isset is incredibly useful.

  • Bryan

    I just downloaded your javascript ebook, but for the life of me, I can not find your PHP book. There is no search on that site and you didn’t give a direct link to your php book. WTF?

    • Hamid

      yo Bryan read his post again:

      If that’s you, I hope you’ll check it out when it releases in the extremely near future! We’ll keep you posted.

      GL:-)

    • http://rockablepress.com/ Naysan

      Hi Bryan,

      Andrew’s book called ‘Getting Good with PHP’ is going to be released sometime this week!

      You can download the first 15 pages of his book here: http://bit.ly/MyOt75

  • waiyan

    This tutorial is so good for me ( php beginner). Thank advanced Autor.

  • waiyan

    This tutorial is so good for me ( php beginner). Thank advanced Andrew Burgess.

  • Jonathan

    It is worth noting that strip_tags() does not remove attributes and thus cannot be considered safe from untrusted sources.

    For example something like:
    <strong onmouseover=”alert(‘xss’);”>text</strong>

    Using:
    echo strip_tags(‘<strong onmouseover=”alert(‘xss’);”>text</strong>’, ‘<strong>’);

    Will not remove the onmouseclick attribute and thus be unsafe.

    Because of this the second parameter of the strip_tags function should basically never be used.
    If you need to sanitize html use a library like HTMLPurifier which will secure the data as well as correct faulty html.

    As for date() vs. strftime() I think it is better to use the DateTime object instead of either one. It is more flexible than either one and doesn’t have a lot of the drawbacks. On a 32bit system time timestamps used by both date() and strftime() are limited to the 32bit integer size and thus can only be between Fri, 13 Dec 1901 20:45:54 GMT and Tue, 19 Jan 2038 03:14:07 GMT.

  • http://www.madansapkota.com Madan Sapkota

    No Shared server are upgraded to PHP 5.4 not even to 5.3 …

    $sites = ["Nettuts+", "Psdtuts+", "Mobiletuts+", "Mactuts+"];

    this is not supprted < PHP 5.4

    Just use

    $sites = array(“Nettuts+”, “Psdtuts+”, “Mobiletuts+”, “Mactuts+”);

  • A reader

    “You don’t want random JavaScript running”

    strip_tags doesn’t filter nested HTML attributes in allowed tags. For examle, you can still use Javascript events like onmouseover to inject Javascript.

    <strong onmouseover=”alert(‘Hello, World’)”>

    A warning about it can be foud in the manual page.

  • http://andrewburgess.ca Andrew Burgess
    Author

    Thanks guys!

    Everyone mentioning date vs. strftime: Like Francisc said, “date() has a few bugs and doesn’t support locale.” Another good reason (for me, at least) to use strftime is that it has some implementation in several different programming languages, so you can use the same formatting tokens whether you’re writing Ruby or PHP (or Python or C, or even JavaScript with the help of a library).

    @Leonardo: Right! Thanks for clarifying that.

    @Luke S & @Bryan: It’s be out so incredibly soon!

    @A reader: Thanks for clarifying that; now that you mention it, it would probably have been a good idea to link to the manual page for each function. :)

  • http://inkwell.dotink.org Matthew J. Sahagian

    I believe list is a language construct, not a function.

  • Brendon

    Looking forward to the book Andy, enjoyed the JavaScript one … I use isset almost every day :)

    Cheers

  • https://creditorwatch.com.au Dale Hurley

    Hi

    Nice to have articles like this. Would like to see more. There was some good reminders like range.

    Dale

  • http://www.wojciechfornal.com Wojciech Fornal

    It’s worth mentioning one subtlety of isset while checking keys in the array. When a certain key exists in an array and it has a value of NULL, isset will return false:

    $some_array['some_key'] = NULL;
    isset($some_array['some_key']); // false

    For checkin if a key exists no matter what value it has/references, one should consider array_key_exists function.

    Cheers

  • http://www.cotonti.com Gert Hengeveld

    In the Cotonti CMF, we use a wrapper function for date() to support localization. It’s a bit slower but it allows developers to write their own translations and time formats, because it uses localized formats too. For example you can pass ‘date_full’ as format which in en_US will be Y-m-d but in nl_NL will be d-m-Y.

    The cot_date() function: https://github.com/Cotonti/Cotonti/blob/master/system/functions.php#L3033
    Supported localized formats: https://github.com/Cotonti/Cotonti/blob/master/lang/en/main.en.lang.php#L373

  • L

    Thx for art.
    Function 3: strftime – There is no info that this function support locale.
    Function 2: strip_tags – it does not make input secure

    Add link to the manual page for each function,

    Remember security is important.

  • James Rubineli

    The first one (array_rand) doesn’t work here. I got a syntax error.

  • James Rubineli

    I don’t get it.

    This doesn’t work:
    $sites = ["Nettuts+", "Psdtuts+", "Mobiletuts+", "Mactuts+"];

    But this, instead, works.
    $sites = array(“Nettuts+”, “Psdtuts+”, “Mobiletuts+”, “Mactuts+”);

    My PHP Version is 5.3.8.

    • Eric

      If I’m not mistaken, the first form only works on PHP Version > 5.4

  • TreeDee

    If you’re a beginner and you don’t know isset, you’re gonna have a bad time !!

  • http://www.twitter.com/1koech Tintale

    As an intermediate php developer, here are some php functions i use quite often:
    1. empty();
    Useful when checking for user input while working with forms:

    if(!empty($_POST['username'])) {
    //field has content, do something
    } else {
    //no input, do something else
    }

    2. function_exists()
    Useful for checking whether a required library, e.g curl is available or not. Quite handy when writing apps that depend on libraries across deferent hosting environments.

    if (!function_exists(‘curl_init’)) {
    //Throw an exception
    throw new Exception(‘App needs the CURL PHP extension.’);
    }

    • http://andrewburgess.ca Andrew Burgess
      Author

      Good ones!

    • http://en.funivan.com funivan

      if(isset($_POST['additional_items'])){
      //additional items
      }

      isset is also useful.

    • nands

      1. It’s incorrect, and will throw an undefined index notice.
      Best practice, either array_key_exists and isset.
      E.g.: if (array_key_exists(‘username’, $_POST) === false):

    • http://www.facebook.com/adi.florence Adipure Nugroho

      wow,incridible. i’ve never think before. i just know it. thank

  • http://rockablepress.com/ Naysan

    Hey guys,

    Andrew’s book called ‘Getting Good with PHP’ is going to be released this week!

    You can download the first 15 pages of his book here: http://bit.ly/MyOt75

    • http://www.tomtotom1.mysite.com Walter Thomas Jr

      what do you mean….

  • http://www.keithbluhm.com Keith

    This is pretty useless. Out of over 5,000, these 7 are notably super-handy?

  • http://andrewburgess.ca Andrew Burgess
    Author

    Madan Sapkota and James Rubineli: Sorry about that! As you’ve pointed out, the array should be wrapped with array(), and not []. Accidentally used the JavaScript syntax there, which is actually valid PHP for PHP >=5.4 :).

  • http://rockablepress.com/ Naysan

    Heads-up!

    Andrew’s book ‘Getting Good with PHP’ is now available:

    http://rockablepress.com/books/getting-good-with-php

  • http://www.pinaysexygoddess.com Pinay Sexy Goddess

    range() would be useful!

  • http://www.tom-elliott.net/ Tom

    As someone who’s being using PHP for 5 years, I only knew 2 of these functions!

  • http://www.ludusinteractive.co.uk Daniel Jenkins

    This is a bit awkward, I’d say I was pretty well versed in PHP, didn’t know about the “list” function!

  • Nick

    $sites = [];
    Doesn’t work.

  • http://alicethetic.com/ Alice

    range()
    Will definitely come in handy and save me some time.

  • http://comradedeveloper.blogspot.com/ Comrade

    Why not, 7 categories of major functions for beginners? String Functions (str_replace(), strpos(), explode(), implode()), array functions, file functions, io, date/time, database, etc.

  • ravikant sharma

    Sorry about that! As you’ve pointed out, the array should be wrapped with array(), and not []. Accidentally used the JavaScript syntax there, which is actually valid PHP for PHP >=5.4 :).

  • http://allsnoringcures.com Sisir

    I will vote for explode(), implode(), preg_replace() and shuffle() The list could’ve been longer.

  • http://www.giocc.com Gio Cielo

    It should also be noted that using basename($filepath) alone to retrieve files is vulnerable to a directory traversal attack. So, whenever retrieving files, you use a composite of basename and realpath: basename(realpath($filepath)).

  • daniel

    great. keep it up.

  • Lúdio

    Cool :) thank you

  • Paramesh

    Thanks

  • http://twitter.com/SancakYuksel Sancak Yuksel

    Thanks :)

  • Christian

    okay

  • ECode

    Thanks! There was couple functions what I didn’t know and very useful!

  • cranknet

    Thank You !

  • http://www.facebook.com/fernandocarvalhos Fernando Santana

    Great, in array_rand. How do I upgrade from time to time, always updating, do with javascript?

  • Kyle

    I have often used isset function to check whether the variables are empty or not. Other than that all functions are new to me, Thank you for pointing out the important ones.

  • http://www.facebook.com/adi.florence Adipure Nugroho

    i think this is useful

  • http://twitter.com/NikkelClark Nikkel Clark

    The basics, if you don’t know these then make sure you understand them now! It will help you in the long run.

  • http://www.facebook.com/yogeshsaroya Yogesh Saroya
  • User

    Great Work