search
HomeBackend DevelopmentPHP TutorialBasic syntax structure of PHP conditional statements_PHP tutorial

Basic syntax structure of PHP conditional statements_PHP tutorial

Jul 13, 2016 am 10:50 AM
elsephpunderandBasicconditionstatementGrammatical structuresoperator

The conditional statements in PHP are if else, switch and ternary operator. Let me introduce to you some syntax of these conditional statements.

Basic syntax structure of if single branch

if(conditional expression){

//Execute statement;

}

if double branch

Basic grammatical structure

if(conditional expression){

//Execute statement;

}else{

//Execute statement;

}

if multiple branches

The basic grammatical structure is

if(conditional expression){

//Execute statement;

}else if (conditional expression){

//Execute statement;

}else if(conditional expression){

//Execute statement;

}else{//There may be more else if
//Execute statement;
}

☞ Please note the above structure:

1) else if can have one or multiple

2) else can be omitted

Example

The code is as follows Copy code
 代码如下 复制代码



帐号:

密码:



if($account == "lord" && $password == "pass"){
    echo "欢迎 $_POST[account], 你的密码是 $_POST[password]";
}elseif($_POST[account] == "god" && $_POST[password] == "dog"){
    $y = date("Y") - 1911;
    $m = date("m");
    $d = date("d");
    echo "欢迎 $_POST[account], 今天是民国".$y."年".$m."月".$d."日";
}else{
    echo "登入失败:


输入的资料:
帐号: $_POST[account]
密码: $_POST[password]";
}
?>


Account:
Password:

if($account == "lord" && $password == "pass"){

echo "Welcome $_POST[account], your password is $_POST[password]";
}elseif($_POST[account] == ​​"god" && $_POST[password] == "dog"){
$y = date("Y") - 1911;
$m = date("m");
$d = date("d");

echo "Welcome $_POST[account], today is the Republic of China".$y."Year".$m."Month".$d."Day";

}else{

echo "Login failed:
Input information:
Account: $_POST[account]
Password: $_POST[password]";

}
?>

switch branch statement

Basic grammatical structure

switch(expression){

case constant 1:
 代码如下 复制代码
  else {
    echo "i is not equal to 0, 1 or 2";
}
?>
//Execute statement; break; case constant 2: //Execute statement; break; defual: //Execute statement; break; } Example The following two examples use different methods to achieve the same thing. The first uses if...elseif...else statements, and the other uses switch statements.
The code is as follows Copy code
else { echo "i is not equal to 0, 1 or 2"; } ?>

The meaning of the above PHP code is: if the variable $i is equal to 0, then output "i equals 0"; if the variable $i is equal to 1, then output "i equals 1"; if the variable $i is equal to 2, then Output "i equals 2"; if neither, output "i is not equal to 0, 1 or 2".


Comparison of switch statement and elseif statement
In a switch statement, the condition is evaluated once and then compared to each case, whereas in an elseif statement, the condition is evaluated again. If your conditions are more complex, or there are multiple loops, it will be faster to use the switch statement.

The code is as follows
 代码如下 复制代码

isEmpty="";

$isEmpty=" 非空 ";

$test = empty($isEmpty)?"":trim($isEmpty);

Copy code

isEmpty="";

 代码如下 复制代码

if (empty($isEmpty)) //条件成立

{
    $cookie = "";
}
else

{

    $cookie = trim($isEmpty);

 

}


 

$isEmpty=" not empty ";

$test = empty($isEmpty)?"":trim($isEmpty);




Ternary operator?: According to the previous condition empty($isEmpty)true or false, when the condition is true, calculate the expression after ?, and when false, calculate the expression after:.


If you are not used to it, you can change it to the following code

The code is as follows Copy code

if (empty($isEmpty)) //Condition is true


{
$cookie = "";
}
else

{

$cookie = trim($isEmpty);



}

☞ Please note: 1) There are one to many case statements 2) The defaul statement does not need to be included (according to the business logic of your own code) 3) Usually, after the case statement, break is required to indicate exiting the switch statement 4) Type of constant (int, float, string, Boolean) Supplement Comparison operators. $a == $b equals TRUE if $a equals $b.          $a != $b    Not equal TRUE if $a is not equal to $b. $a $b does not equal TRUE if $a is not equal to $b.           $a $a > $b is greater than TRUE if $a is strictly $b.           $a $ A & GT; = $ B greater than or equal to True, if $ a is greater than or equal to $ b.           Logical operators. $ A and $ B and (logic and) true, if $ a and $ B are True. $ A or $ b or (logic or) true, if $ a or $ b is True.                         $a xor                                                                                                                                     ! $a   Not (logical NOT)   TRUE if $a is not TRUE. $ A && $ b and (logic and) true, if $ a and $ B are True.             $a ||   $b     Or (logical OR)   TRUE if either $a or $b is TRUE.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632630.htmlTechArticleThe conditional statements in php are if else, switch and ternary operator. Let me introduce these conditions to you. Some syntax of statements. The basic syntax structure of if single branch if (conditional expression) {...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use