Uncommon PHP tips

I love PHP. Here are some tips that are not so common or not so easy to find.

Single vs. double-quotes

Don’t overthink it, especially with newer PHP versions.

Unless you process millions of rows or need to evaluate thousands of strings per second, it’s irrelevant.

The double quotes allow for parsing variables inside, unlike single quotes:

$var = "echo";
echo 'simple string {$var}' . PHP_EOL;// simple string {$var}
echo "advanced string with my variable: {$var} \n";// advanced string with my variable: echo

Choose one style and stick with it. Alternatively, nowdoc and heredoc syntaxes can handle multiline strings.

I would not recommend thinking in terms of micro-optimization. The maintenance is more important to me:

isset() is neither !empty() nor is_null()

It’s a typical mistake that often leads to more complicated maintenance:

$p = "";
if (!empty($p)) { // does not work here
    echo 'is not empty';
}
if (isset($p)) {
    echo 'is set and is not null.';
}
if (!is_null($p)) {
    echo 'is not null.';
}

$p is empty even if it’s not null. isset() only checks if the variable is declared and not null, not if it’s empty. It gets worse when null can be a valid value for $p.

is_null() is the opposite of isset(), but it only applies to existing variables. Please don’t use it to check whether a variable exists or not.

isset() or array_key_exists()?

Let’s create a simple array:

$myArray = [
    "response" => "ok",
    "some_key",
];

var_dump(isset($myArray["some_key"]), array_key_exists("some_key", $myArray);// false false

Both functions return false. Maybe it is not what you expected.

If so, that’s great, because we are about to see why. Let’s add a value this time:

$myArray = [
    "response" => "ok",
    "some_key" => null,
];

var_dump(isset($myArray["some_key"]), array_key_exists("some_key", $myArray);// false true

The problem was some_key was actually not an array key but a value for the key “0”:

$myArray = [
    "response" => "ok",
    "some_key",
];

var_dump(array_keys($myArray)); // response, 0
var_dump(array_values($myArray));// ok, some_key

isset() does quite the same job as array_key_exists() here, but it also checks if the value is not null for the specific key.

If you only want to check if an array has a specific key regardless of its value, you’d better use array_key_exists().

Just don’t add this lengthy and less readable code:

$myArray = [
    "response" => "ok",
    "some_key" => null,
];
if (in_array("some_key", array_keys($myArray))) {
    // some code
}

PHP Developers prefer isset() because it’s significantly faster. To take the best of the two functions, it’s possible to write:

if (isset($myArray['some_key']) || array_key_exists('some_key', $myArray)) { 
    // some code
}

The engine evaluates the right part of the condition (array_key_exists('some_key', $myArray)) only if the value of $myArray['some_key'] is null. This way, you don’t miss anything.

In any case, you must understand the difference between isset() and array_key_exists() to avoid expensive errors in your conditions.

Deprecated PHP snippets

Make sure you add at least your PHP version in the search keywords to avoid misleading code samples.

For example, PHP snippets to validate email addresses are all over the web. They often use regular expressions while the following seems a much better alternative:

// since PHP 5.2
print_r(filter_var($email, FILTER_VALIDATE_EMAIL) !== false);

Source: PHP documentation - filter_var()

Besides, there many other validations you can do with filter_var().

Nullable is not null

In PHP, we can write that:

// since PHP 7.1
function greet(?string $message)
{
    print_r($message);
}

It’s called nullable types, and it’s awesome because it’s available for all types, but it does not mean you can skip the parameter at all:

greet();// fatal error

It simply means the value of $message can be null. If you want a default value, use a default value:

function greet(string $message = "Hello")
{
    print_r($message);
}
greet();// Hello

Wrap up

PHP can be tricky. Always keep your eyes open.