Executing a query with or without bound variables

Posted on

Problem

I know there’s a more compact way of doing the following code but I haven’t been coding PHP in a while and I completely forgot how. I’m pretty sure it’s to do with : and ?‘s but I’m unsure.

Basically, if $bind has a value add $bind inside of execute() otherwise just don’t.

//Execute Binded Query;
if($bind != false) {
    $query->execute($bind);
} else {
    $query->execute();
}

Solution

Try the ternary operator for a one-liner.

$query->execute($bind ?: array());

Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. So in this case, if bind is not false (thus true), it will return bind, and else empty array.

I know theres a faster/easier more inline/1liner way of doing the following code

Can I and should I are two completely different things.

Can you make this a one-liner? Yes.

Should you? No.

When calling a function as a result of a condition, you are dealing with flow control. The Ternary Operator makes this harder to read. The if statement makes it obvious.

This is very clear:

if (condition) {
    doSomething();
} else {
    doSomethingElse();
}

Whaaaaaaa… (scratches head)

(condition ? doSomething() : doSomethingElse());

Using a Ternary Operator in an assignment can make things easier to read and shorter as well:

$bind = condition ? array() : $otherArray;

$query->execute($bind);

Cramming the Ternary Operator in the argument to a method call just obfuscates your code. I would recommend using the Ternary Operator in your assignment to the $bind variable, or another if statement earlier in your code and just blindly calling $query->execute($bind).

As previously mentioned by @GregBurghardt, just because you can doesn’t mean you should. All of his reasoning holds true, and code readability should be your primary concern when writing code. Code shortness is one of the methods you achieve this, but if the code becomes too dense it is actually detrimental to the readability. Which, in turn, will lead to more problems with bugs and inefficient coding(!).

I recommend doing it in the following manner. It will keep the repeated code to a minimum, while still ensuring that there are no warning/notices about missing variables or erroneous data. Plus it’s very clear what the code does, and easier to understand why. (Comments can/should be added to further clarify why.)

if (!isset ($bind) || typeof ($bind) != 'array') {
    $bind = array ();
}
$query->execute ($bind);

What you are attempting is called “premature optimization”, and is quite discouraged in programming. Not only because it has no benefit for the runtime of the code, or anything else really, but also because the high risk of making the code consume even more resources.

In this particular case the IF-construct is faster than the ternary operator. Not by much, granted, but it is still faster. Which makes the change proposed not only more difficult to read, but also contrary to the desired effect. Basically it will be neither faster nor easier, though it will be more “inline/one-liner”. Though, I don’t think that sacrificing both speed and simplicity is worth it to get it on one line.

Example: Which of these two methods do you think is the fastest, and why?

// Method 1:
function HK3 ($search, $string) {
    if (empty ($search)) {
        return $string;
    }
    $string = trim ($search);
    $string = preg_quote ($string);
    $string = explode (" ", $string);
    $string = array_map ("custom_highlight_string_fixer", $string)
    return preg_replace ($string, '$1<b>$2</b>', $string);
}

function custom_highlight_string_fixer ($String) {
    return "/([\s><])($String)(?=[\s><\n\r,.!?]|\z)/i";
}

// Method 2:
function BTH_HK ($needle, $haystack) {
    if (empty($needle)) return $haystack;
    return preg_replace ('/([\s><])(' . str_replace(' ', '|', preg_quote ($needle)) . ')(?=[\s><\n\r,.!?]|\z)/i', '$1<b>$2</b>', $haystack);
}

If we go by your initial presumption, that anything in one line is faster than something that spans multiple lines, the second method should be loads faster than the first. Even if we look at the number of functions calls, that should be true too.

In reality, however, it’s the first method that is the fastest one. This is because it’s written with the knowledge of how every line of code works in the inner bowels of PHP, and an understanding of how that affects the data which is fed to it. Of course, that also means that it can vary who’s fastest depending upon the exact data which you feed them.

Which is the only way to properly optimize code, and why it is generally discouraged to attempt for those who are still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *