PHP if Statements

PHP Tutorial

PHP if Statements

In PHP if Statements is used to execute a block of code only if a condition is true.


1. Basic if Statement

Syntax:


Example:


 


2. if…else Statement

Runs different code if the condition is true or false.

Syntax:


Example:


 


3. if…elseif…else Statement

Use it when you have multiple conditions.

Syntax:


Example:


 


4. Nested if Statements

An if inside another if.

Example:


 


5. Shorthand if (Ternary Operator)

Syntax:


Example:


 


6. Null Coalescing Operator (??)

Useful to check if a variable exists.


 


7. Alternate Syntax for HTML Code

Useful for PHP inside HTML templates.



📘 Examples for Practice

Example 1: Check Number is Positive or Negative


 

Example 2: Check Even or Odd


 


🎯 Summary

Statement Purpose
if Run code only if condition is true
if…else Choose between 2 blocks
if…elseif…else Multiple conditions
Nested if One if inside another
Ternary Short if…else
?? Check undefined/null variable

If you want, I can continue with the next topic:

👉 PHP Switch Case
👉 PHP Loops
👉 PHP Arrays
👉 PHP Functions

You may also like...