Create a Boolean variable in PHP
If you aren’t familiar with Booleans, they are basically toggle of 1 or 0 to determine if a variable is true or false.
We won’t be using our constants anymore, so lets go ahead and remove them for now.
And we’ll create a new variable named $hasPosts
. You can name booleans whatever you want, but it’s a great convention to prefix them with either an is
or has
. This self-documents this variable as a boolean, which can be helpful in this loosely-typed language.
Let’s set it equal to true.
$hasPosts = true;
Before we continue, let’s learn about another very frequently used PHP function called var_dump()
.
This function dumps the output of a variable to the screen. It differs from other commands because it dumps out more verbose information about a specific variable or expression.
<?php var_dump($posts) ?>
When we refresh the screen, we’ll see that not only the value of the variable is outputted, but also the type. This can be extremely useful when debugging your code.
Also note how I didn’t use a short echo tag here. That is because var_dump()
automatically echos out whatever you pass to it.
Let’s change true
to false
. And of course we will see it update.
Now, let’s add an exclamation to the front! This reverses the polarity of this variable, essentially making false
⇒ true
or true
⇒ false
. This can be useful when you want to return the opposite value of what is passed to it.
You an also pass an expression to a variable. Using a double ampersand &&
is an AND
operand, which means if both sides of the operand are true, then it will return true
.
$hasPosts = $numPosts && $title;
If one of these values is false:
$hasPosts = $numPosts && !$title;
Then this evaluates to false
, since both expressions must be true to return a truthy result.
Similarly, we can pass it a double pipe ||
which makes this an OR
operand. So, if either one or the other of these values is true, the entire expression will evaluate to true
.
For now, let’s return the expression $numPosts
greater than 0, so whenever we have any number of posts greater than 0, this will be true.
$hasPosts = $numPosts > 0;