PHP if else and elseif: How to Use Conditional Statements
Learn how PHP if, else, and elseif statements work with clear examples. Build confidence writing conditional logic in your PHP code.


PHP IF ELSE
In PHP, the if, else and elseif structures are used in a way similar to other programming languages. The if statement checks whether variables meet the specified conditions. Depending on the result of the condition, if it returns TRUE, the block inside the first curly braces is executed. If the condition returns FALSE, the ELSE and ELSEIF branches can be tried.
Now let’s try to understand these situations with a few examples..
$kullaniciAdi = "admin";
<?php
if ($kullaniciAdi == "admin")
{
echo "Merhaba Yönetici";
}
else
{
echo "Yönetici değilsiniz";
}
?>
For example, when we define a variable like $kullaniciAdi = “admin” and assign the value “admin” to it, we check inside the IF block whether the kullaniciAdi variable is equal to the value “admin”. If this condition is true, the first block is executed and the administrator greeting is printed to the screen. Otherwise, the ELSE block runs and the message saying that the user is not an administrator is printed to the screen.
Using PHP If, Else and Elseif
Unlike the previous example, we generate random numbers using the rand function. Then, if the value of the variable evaluated inside the IF block is not TRUE, we can add multiple elseif branches to define what should happen in different conditions.
$sayi = rand(1,10);
if($sayi < 10)
{
echo "Sayı 10'dan küçüktür.";
}
elseif($sayi == 10)
{
echo "Sayı 10";
}
else
{
echo "Sayı 10'dan büyüktür.";
}
- PHP Lessons – Foreach Usage and Examples
- Array Usage and Examples
- Operators
- What Is PHP Heredoc and What Is It For?
- You can review examples on the official PHP website
Share it if it helped


