Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 4 / 68

Conditionals (if statements)

In this lesson you will learn how to write if statements in PHP so your program can branch based on a condition. This is for anyone searching for "PHP if statement syntax" or "PHP elseif".

if / elseif / else splits your logic by condition. It helps to picture it as translating an everyday decision such as "if it is raining, take an umbrella" into code. Note that elseif is written as a single word, which differs slightly from JavaScript.

The sample code prints one of three messages depending on $score using if / elseif / else. JavaScript writes else if as two words; PHP writes elseif as one. Keep that in mind as you learn the shape of this construct.

A common stumbling block for beginners is the difference between == and ===. Comparisons use operators such as == and ===, where === compares the type as well as the value. Comparing the string "1" with the number 1 is where the difference tends to surprise people.

In real-world development if statements appear in almost every program, from switching the display based on login state to validating input. Getting PHP's elseif spelling right is the foundation of readable code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)