7 things I wish I knew learning PHP

Way back in 2009, I decided that my friends and I, who hoped one day to be game design entrepreneurs, needed a web site.  I knew a bit of HTML, so naturally, I decided I would make it.

Looking back, I don’t know how I made that decision, but over a few weeks I found myself diving in headfirst learning CSS and PHP.  Over time, I’ve found a few tips I wish I could’ve passed to my younger, slightly experienced self.

1. String and array manipulations

PHP has a great variety of string functions and array functions.  There are some particular ones I wish I knew about.

  • explode and implode – Explode splits a string into an array with a delimiter, and implode does the opposite.  Examples:
    explode(',', 'Comma,delimited,list')
      => array('Comma', 'delimited', 'list')
    implode(', ', array('a', 'item 2', 'hello'))
      => array('a, item 2, hello')
    array_map(trim, explode(',', "1, 2, 3,   4,5, \n\t twenty 6,7"))
      => array('1', '2', '3', '4', '5', 'twenty 6', '7') 
  • crypt – A handy and quick way to encrypt a string.  Note that this is a one-way encryption.
  • trim – Clean whitespace from the beginning and end of a string.  It also has two variants, ltrim and rtrim, which clean whitespace from only the beginning or end of the list, respectively.
  • $a[] – Compact syntax for appending an element.  Basically, the following are all equivalent:
    $a[] = 5;
    $a[count($a) - 1] = 5;
    array_push($a, 5);

It’s also very handy to learn regular expressions.  Cats who Code has a helpful article on some common regular expressions.

There are a few others worth mentioning, but check the reference pages and you’ll probably find what you’re looking for.

2. filter_var and htmlspecialchars

filter_var allows you to test and sanitize a string according to some predefined format.  For example, you can use it to check if an e-mail address or number given by a user is valid and also clean it up at the same time (ex. “Number -5” would be sanitized to “-5,” then checked to see if it’s a valid number).

While filter_var filters input, htmlspecialchars filters output.  You should use it anytime you print text into an HTML document that might contain angle brackets or other characters that can interfere with HTML.

3. PDO

PHP Data Objects, or PDO, provide an abstract interface for SQL databases, like MySQL, PostgreSQL, MySQL, et al.  Here’s an example of connecting to an SQLite database:

    $pdo = new PDO('sqlite:test.sqlite3');

    $query = 'SELECT name, color, calories
              FROM   fruit
              WHERE  calories < :calories OR color = :color

    $statement = $pdo->prepare($query);

        'calories' => 500,
        'color'    => 'Orange'

    $fruits = $statement->fetchAll();

    foreach ($fruits as $fruit)
        echo $fruit['name'], '<br>';
catch (PDOException $e)
    echo 'Database error: ', $e->getMessage();

4. SQLite

SQLite is very useful, as it requires almost no configuration, and since the databases are stored in files, they’re easy to manipulate and move.  Also, if a very common action is opening a database to select some values, like configuration values or the like, SQLite has extremely fast selection speed.

I’m not encouraging SQLite as a superior alternative to a database system like PostgreSQL, but instead as a lightweight and rich data storage and retrieval tool.  On a side note, if you’re using PDO, transitioning from one database to another is painless (so plus one for PDO!).

5. How switching in and out of PHP blocks works

When I began programming in PHP, I assumed that the following code would not work:

    $x = array(1, 2, 3);

    if (count($x) == 3):
X has three elements.

    echo count($x);

First, I assumed that you couldn’t end a control structure in one PHP block and finish it in another, and I also thought that $x would go out of scope and not be there in the second block.

Later, I realized that PHP is basically a very output-oriented language.  Essentially, the following is “Hello, world!” in PHP:

Hello, world!

I have yet to find a more concise and compact way to express output in a programming language, and that’s PHP’s purpose.  I thought the engine would pick out PHP blocks and execute them, replacing them each as indivisible blocks of code.  I now understand that the code example I showed earlier is more like this:

    $x = array(1, 2, 3);

    if (count($x) == 3)
       echo 'X has three elements.';

    echo count($x);

6. Capturing output

It turns out you can capture the standard output resulting from executed PHP code using ob_start and its related functions.  Here’s an example:

echo 'Hello, world!<br>';

  echo 'This output will be captured.<br>';

    echo 'This output will be captured in a nested manner.<br>';

    $out1 = ob_get_contents();

    echo 'There were ', strlen($out1), ' characters in the string ', $out1, '<br>';

  echo 'This output will also be captured.<br>';

  $out2 = ob_get_contents();

echo 'I will now print the contents of out2: ';
echo $out2;

Would result in:

Hello, world
I will now print the contents of out2:
This output will be captured.
This output will be captured in a nested manner.
There were 48 characters in the string "This output will be captured in a nested manner."
This output will also be captured.

This is particularly useful with functions that always write to standard output, like var_dump, and you want to somehow manipulate or store its output.

7. Coalescing, error-suppressing, and lazily evaluating operators

A common source of errors and unreliability of PHP programs could probably be contributed to laziness.  It is so easy to just take an invalidated number input and go with it or not check for empty values.

The first operator is the coalescing operator, ?:, which simply takes, on the left, a possibly empty value, and on the right, a default.  If the possibly empty value is false, null, etc. the result of the expression will be the right hand value; otherwise, it will be the left hand value.

The error-suppression operator, @, also affectionately called the shut-up operator, suppresses pesky warnings from evaluating an expression.  If you’re tempted to use it, you should first consider fixing the error in the first place, but I find it useful when something’s default value (like how accessing a nonexistent array key returns null) is what I want.

Lazy evaluation (also called non-strict evaluation, as opposed to eager or strict evaluation) refers to not evaluating something until strictly necessarily.  For example, if you have “True or ?,” you can tell the result must be True, no matter what ? is.  In PHP’s case, the ? wouldn’t even be evaluated.  Similarly, “False and ?” would always be False, so ? wouldn’t be evaluated.

I was pleased to find the previous three operators because it makes providing defaults and making robust code more convenient, which means I’m more likely to develop good habits.  Here’s an example, also including some logical operator tricks:

is_array($a) or die('$a is not an array!  Terminating program.');

($b == 0) and die('$b is equal to 0!  Terminating program.');

@$_GET['page'] ?: 'If $_GET[page] is not defined, I will be returned.';

foreach (@$a ?: array() as $v) {
    echo 'If $a is false, null, or undefined, it will be as though it contained an empty array.';

This makes it easier to have good habits, since error checking is less of a pain.

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s