شرط if...else...elseif PHP
- Previous Page عناصر ریاضی PHP
- Next Page PHP Switch
شرطهای کد برای اجرای عملهای مختلف بر اساس شرطهای مختلف استفاده میشوند
شرطهای PHP
در هنگام نوشتن کد، اغلب میخواهید برای تصمیمات مختلف، عمل متفاوتی انجام دهید. میتوانید از شرطهای کد برای این منظور استفاده کنید.
در PHP، میتوانیم از شرطهای زیر استفاده کنیم:
- شرط if - اگر شرط مشخص به true باشد، کد اجرا میشود
- شرط if...else - اگر شرط true باشد، کد اجرا میشود؛ اگر شرط false باشد، کد دیگری اجرا میشود
- شرط if...elseif....else - اجرای بخشهای کد بر اساس دو یا بیشتر شرط
- شرط switch - انتخاب یکی از بخشهای کد برای اجرا
PHP - شرط if
شرط if برایدر حالت که شرط مشخص به true باشدکد اجرا میشود.
Syntax
if (condition) { کدی که در حالت true قرار دارد، اجرا میشود; }
در این مثال، متن "Have a good day!" نمایش داده میشود، اگر زمان فعلی (HOUR) کمتر از 20 باشد:
Example
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?>
PHP - شرط if...else
Use the if....else statementExecute code when the condition is true,Execute another piece of code when the condition is false.
Syntax
if (condition) { Code executed when the condition is true; } else { Code executed when the condition is false; }
If the current time (HOUR) is less than 20, the following example will output "Have a good day!", otherwise output "Have a good night!":
Example
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - if...elseif....else statement
Use the if....elseif...else statement toExecute different code based on two or more conditions.
Syntax
if (condition) { Code executed when the condition is true; } elseif (condition) { Code executed when the condition is true; } else { Code executed when the condition is false; }
If the current time (HOUR) is less than 10, the following example will output "Have a good morning!", if the current time is less than 20, then output "Have a good day!". Otherwise, output "Have a good night!":
Example
<?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } elseif ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - switch statement
We will learn the switch statement in the next section.
- Previous Page عناصر ریاضی PHP
- Next Page PHP Switch