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

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years 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.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today