1. 16
    Conditionally execute PHP code with an if statement
    1m 48s

Conditionally execute PHP code with an if statement

Mark Shust
InstructorMark Shust

Share this video with your friends

Send Tweet
Published 10 months ago
Updated 6 months ago

Every programming language has the concept of conditional statements. In this lesson, we will go over how to create if statements in PHP.

Instructor: [0:00] Every programming language has the concept of conditional statements, if this, then that. PHP is definitely not any different. To write a condition we'll, of course, need to be within a PHP tag. We can write everything within one code block just like this or use two or more inline PHP statements.

[0:20] For now, we'll just use this block method. It is more common to write code like this in PHP programs. Let's type if, and afterwards comes an open and closed parentheses. Within these parentheses is a condition. We can write a condition inline just like this, and this is usually how most developers write if statements.

[0:43] Note how we already have this hasPosts variable though, already assigned to the result of the same condition. If we didn't already have this within a variable, it would be a good idea to write our condition and store the result within one.

[0:59] Let's take the hasPosts variable and replace our condition with it. Not only does this make our code easier to read, but it also makes our code read more like human language. If hasPosts is a lot easier to understand than if numPosts > .

[1:18] The variable name also provides meaning to this condition. It's self-documenting the code along the way, which helps us avoid bugs in the future.

[1:26] Next comes an open and closed bracket. Within this bracket is where we will execute our code if the condition is true. In this case, let's just echo out postsExist. This is currently a valid if statement. If we save and refresh the page, we will see that postsExist message.