Understanding PHP Operators of Logic, or || and && and ! a lot more

There are a lot of different PHP operators. Some are PHP comparison operators, and work like math you’re used to. We’ll save those for another time, because our sole focus this time will be PHP logical operators. That is the logical “and” and “or” of boolean logic.

There are three big ones: “and” (&&), “or” ||, and “not” !. Let’s get to it.

Why PHP Logical Operators Matter & What They Are

To the surprise of many people afraid of programming, a lot of what you do when programming is create and solve simple logic puzzles. At the risk of oversimplifying, in WordPress we simply store specific data, and then build simple little machine (called “WordPress themes”) to display that data to specific people in specific way under specific conditions. (That’s the role of the “template hierarchy” in WordPress, if I just blew your mind.)

So a lot of WordPress PHP code ends up simply being rules like ‘if the data I’m showing is recent, and I’m showing a “page” post type, don’t show the date on the page.’ These rules must be written in a much more syntactically exact way than we speak them, but the principle is the same. And to understand that syntax, we must know how to say “and” and “or”, so let’s get to it.

The && and AND PHP Operators

In short, you say a PHP “and” with a double ampersand symbol (&&). These two pretzels serve the same role of and in some other programming languages you might be used to. In fact (as someone who’s been writing PHP for 15 years, this surprised me) you can write and in PHP. It evaluates a little different, but the language lists it prominently in its documentation on logical operators.

Why was I surprised that you can say “and” with both the && operator and the keyword and? Because no PHP code I’ve ever read has used the latter, and, format. In fact, I can count on one hand the times I’ve read PHP that used and (or or or xor), and many of them were while I was writing this article. The issue is that and behaves a little differently than most of us think, so it might surprise you from time to time in it’s execution.

Long story short: use && when you want to say and in PHP code.

Now for OR or ||: An Alternative Logical Operator

Another core idea of boolean logic with PHP is “or.” Sometimes there are two preconditions, where either being satisfied makes a thing acceptable to us. Like I said, in WordPress themes that might be “if this is a single post entry, or if it’s an archive page.” And like with and above, you can actually write valid PHP code with a simple: or where you mean that.

But, just the same, we almost never see that in the wild. What we see most frequently is instead the “double pipe” || operator. Again, I didn’t realize until writing this article that or was valid PHP, so you should get used to reading and writing ||.

(Even more rare, there exists an “exclusive or” operator in PHP, written xor. This is the rarest PHP logical operator of all. It’s one I’ve never seen outside of tutorials. It means “if the things that surround me are both true, and never else.” Unless you’re looking to impress people, I’d avoid this, as people aren’t in the habit of reading it.)

Bang (!) is NOT to be forgotten

The last thing you need to know to claim you have a robust boolean language is the presence of the “not.” In PHP, you’ll only write that with a “bang” or “exclamation point,” !. Unlike with && and ||, there exists no linguistically-written version.

It’s important to know that “not” (!) in logical syntax doesn’t “turn it off” but instead “flips it.” So “not true” becomes false, and “not false” becomes true.

What this means is that “the sun equals the moon” is a false statement, but “the sun not equals the moon” is a true statement. The “not” flips the statement.

Examples of Using PHP Operators: ! just && and || in strange places

Enough with the highfalutin words, let’s see some code. We’re going to use a simpler situation to understand PHP conditional logic first, but then we’ll layer in some WordPress conditional tags. WordPress conditional tags are generally very easy to read, so if you’re not familiar this shouldn’t prove a big obstacle.

Understanding PHP Not

The bang operator (!) is pretty easy, so we’ll start there. I’m going to be assuming there exists a PHP function called do_thing, and your question across all our scenarios is not to worry what do_thing does–nothing, it’s a fake function–but just tell me if it will be called or not. So let’s start basic:

if (true) {
    do_thing();
}

Here we’re making do_thing run, because an if (true) always runs. This is the basis of doing all logical operations in PHP. PHP and logic all build up from this being so. Let’s keep going:

if (!true) {
    do_thing();
}

Does do_thing run here? No! Why? Because !true is the same thing as false. And code circled by if (false) doesn’t run.

Alright, so what will happen here?

if (!false) {
    do_thing();
}

Indeed, because “not false” ends up evaluating to “true”, do_thing will run in this code snippet.

Basic PHP And (&&) Usage

OK, so let’s keep with the trend of simple trues and falses. Will do_thing get called here?

if (true && false) {
    do_thing();
}

do_thing will not run in the above code. A boolean “and” in PHP will require that both sides of it evaluate to true for the segment to “emit” a true. So a false statement and true statement are not both true, therefore we don’t follow through and call do_thing.

Here we’ll start to fill in the WordPress “conditional tags”, as they should help us get a little more practical. Let’s think through the following code, which you might see in a WordPress theme file:

if ( is_singular() && !is_page() ) {
    the_date();
}

A little context: the_date is a WordPress function which (inside of The Loop) displays the publication date of the current “post.” That means any “post type” in WordPress: pages, posts, forms, etc. Similarly, is_singular will be true when we’re on a “single post” page, which can include all other post types include pages. And is_page tells us we’re on a page (post type) in WordPress. So, given all that, under which conditions will the date show on this template?

When we’re just looking at one post, and we’re not (that’s the !‘s job, remember) on a page post type.

PHP If Or Operator Example

Let’s move onto a PHP “or” (or ||) example. Let’s just reuse our prior knowledge. First, let’s change the && in our first && exercise to the double-piped “or”:

if (true || false) {
    do_thing();
}

Does do_thing get called? It does. Why? Because one, or the other, of its two sides evaluated to true. And since the first statement was (literally) true, we know that it’ll happen.

And then, under what circumstances will the post’s date display here:

if ( is_singular() || !is_page() ) {
    the_date();
}

It’ll show either if we’re just looking at one single-post page, or where we’re looking at any WordPress post type but a page. This has would mean the date in this scenario has very different, much higher, visibility than the && example.

A Combination and Brain Teaser of PHP Logical Operators

Alright, finally an overly complex example. Again, we’ll make use of some conditional tags for WordPress:

if ( is_author( 'David' ) && !is_search() || is_author( 'Fred' ) && is_singular() ) {
    echo 'David is great!';
}

A quick summary of what might be new here:

  • is_author tells us if the post is by the author whose “nickname” matches what we pass.
  • is_search tells us if we’re seeing a search results page in WordPress
  • echo is a way to display some words in PHP

So, what does this code do? In short, it adds some annoying “graffiti” proclaiming David’s greatness. But when? That this is a little complicated to answer gets to one of the downsides of how complex you can make fairly short boolean statements. Let’s rewrite this code a little, to make it easier to think about:

$post_by_david_not_on_a_search_result = is_author( 'David' ) && !is_search();
$post_by_fred_shown_on_own_page = is_author( 'Fred' ) && is_singular();
if ( $post_by_david_not_on_a_search_result || $post_by_fred_shown_on_own_page ) {
    echo 'David is great!';
}

I don’t want to spend too long expanding an article about PHP conditional operators into one about code styles. But it’s important, because we humans are not all perfect Boolean machines. PHP code should make allowances for how humans think. By breaking this logic down and using some temporary variables, I now understand it. This is a skill that’s important to understand. You can write code that is stupidly simple. I’d argue that you’re a better developer if you do.

Back on the topic of PHP and & or: David is great! will be added on posts by David not showing on search result pages, or on posts by Fred showing on a singular page.

You Now Understand Boolean & PHP Conditional Operators

I hope you’ve followed me all the way through. Boolean operations are one of the most profound bases of PHP code knowledge. If you can function in the modern world, you can understand this stuff. Sometimes, I assure you, the syntax will trip you up. It’ll seem to make simple things impossible.

But if you persist, you’ll master it. The PHP logical or, and, and not are within your grasp just remember what all those symbols mean. Quick recap! Not to be too clever || rude. But you can && will succeed! Best of luck 🙂


4 Responses

Comments

  • Michael says:

    Nice explanation of boolean logic operators, in PHP.

    In your last sentence of the article:
    Quick recap! Not to be too clever || rude. But your can && will succeed! Best of luck ?

    Wouldn’t that mean:
    Quick recap NOT Not to be too clever OR rude. But your can AND will succeed NOT Best of luck ?

    ;p

  • JWP says:

    Please check your description of exclusive or. It is my understanding that one side of the operator must be true but NOT both sides as you have stated.

    And your quick dismissal of the ‘and’ and ‘or’ operators as simply keyboard alternatives to ‘&&’ and ‘||’ is a bit too simplistic. Please review the order of precedence – ‘&&’ is NOT identical to ‘and’.

    Otherwise a good basic discussion.

    JWP

  • WPSelected says:

    I wish to see more blog posts in this clear and informative style.

Add a Comment

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