php conditions

Conditional Constructs in PHP

Posted by

PHP conditional constructs are used to make decisions. Programmers check the different conditions and run blocks of code accordingly. It is one of the key features of any programming language.

The following are the conditional constructs in PHP:

If condition:

PHP if condition is used where one condition is true. It does not show anything if the condition is false.

Syntax:

Let’s take an example:

In the above example, $num is matching the value 10 so the output will be show “The number is equal to 10”. If you will change the value of $num then it will not show any output because the condition will not match.

If..else condition

It executes if the condition is true or false.

Syntax:

Example:

In the above example, the assigned value of the variable($num) is not equal to “9” so else part will be run.

If..elseif..else condition

It is used if you have multiple conditions and run different blocks of code based on those conditions.

Syntax:

Example:

In the above example, the output will be show “20 is greater than 10”.

If the value of $a and $b will same then below mentioned block of code will run:

If the value of $a is less than the value of $b then below mentioned block of code will run:

Switch/Case Statement

The PHP switch statement is used to execute multiple conditions of one statement. It works as a PHP if..elseif..else statement.

Syntax:

Let’s go into more detail on the syntax of the switch statement:

  1. Place a variable or expression within parentheses into the switch keyword and start({) / end(}) curly braces.
  2. Inside the curly braces, write multiple cases and place value to compare.
  3. Write a default construct if the value of the case will not math then the default construct will run.
  4. Write break statement in each case and default statement.

Example:

In the above example, The $operator's value is “+” so the case ‘+’ will run if you change the value of $operator then the blocks of code will run according to that value.

Please write in the comment if you have any queries or suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *