Advertisement
PHP

Quick Tip: 7 Super-Handy PHP Functions for Beginners

by

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!

Related Posts
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Computer Skills
    App Training
    PopClip: Scripting ExtensionsPopclip400
    PopClip is a great utility program that, once you get used to it, is very hard to live without. This tutorial is going to show how to write a scripting extension by making an example extension.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Plugins
    Communicating With the WordPress.org Plugin APIWordpressdotorg plugin api border 400
    Over the last few weeks I have been wondering on how to possibly pull data about my plugins hosted on WordPress.org and display it on my website. The first thing that came to mind was "Web Scrapping" but quite frankly this is a lot of work, feels like going back in time, and is not something a good web citizen should do. In some cases, it could be illegal.Read More…
  • Code
    Plugins
    Creating Client Testimonials With Custom Post TypesCreating client testimonials with custom post types
    If you're running any type of business online, it's a good idea to get your clients' opinions on what they thought about the services you provided. First of all, this can benefit you by giving you feedback on how you can improve aspects of your business, but most of all, it can give you great testimonials, which can help to persuade potential clients to use your services.Read More…