Home » PHP Tutorial » PHP if

Summary : in this tutorial, you’ll learn about the PHP if statement and how to use it to execute a code block conditionally.

Introduction to the PHP if statement

The if statement allows you to execute a statement if an expression evaluates to true . The following shows the syntax of the if statement:

In this syntax, PHP evaluates the expression first. If the expression evaluates to true , PHP executes the statement . In case the expression evaluates to false , PHP ignores the statement .

The following flowchart illustrates how the if statement works:

PHP if flowchart

The following example uses the if statement to display a message if the $is_admin variable sets to true :

Since $is_admin is true , the script outputs the following message:

Curly braces

If you want to execute multiple statements in the if block, you can use curly braces to group multiple statements like this:

The following example uses the if statement that executes multiple statements:

In this example, the if statement displays a message and sets the $can_edit variable to true if the $is_admin variable is true .

It’s a good practice to always use curly braces with the if statement even though it has a single statement to execute like this:

In addition, you can use spaces between the expression and curly braces to make the code more readable.

Nesting if statements

It’s possible to nest an if statement inside another if statement as follows:

The following example shows how to nest an if statement in another if statement:

Embed if statement in HTML

To embed an if statement in an HTML document, you can use the above syntax. However, PHP provides a better syntax that allows you to mix the if statement with HTML nicely:

The following example uses the if statement that shows the edit link if the $is_admin is true :

Since the $is_admin is true , the script shows the Edit link. If you change the value of the $is_admin to false , you won’t see the Edit link in the output.

A common mistake with the PHP if statement

A common mistake that you may have is to use the wrong operator in the if statement. For example:

This script shows a message if the $checke d is 'off' . However, the expression in the if statement is an assignment, not a comparison:

This expression assigns the literal string 'off' to the $checked variable and returns that variable. It doesn’t compare the value of the $checked variable with the 'off' value. Therefore, the expression always evaluates to true , which is not correct.

To avoid this error, you can place the value first before the comparison operator and the variable after the comparison operator like this:

If you accidentally use the assignment operator (=), PHP will raise a syntax error instead:

  • The if statement executes a statement if a condition evaluates to true .
  • Always use curly braces even if you have a single statement to execute in the if statement. It makes the code more obvious.
  • Do use the pattern if ( value == $variable_name ) {} to avoid possible mistakes.

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php if statements.

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement - executes some code if one condition is true
  • if...else statement - executes some code if a condition is true and another code if that condition is false
  • if...elseif...else statement - executes different codes for more than two conditions
  • switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement executes some code if one condition is true.

Output "Have a good day!" if 5 is larger than 3:

We can also use variables in the if statement:

Output "Have a good day!" if $t is less than 20:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • PHP History
  • Install PHP
  • Hello World
  • PHP Constant
  • Predefined Constants
  • PHP Comments
  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope
  • If Condition
  • If-else Block
  • Break Statement
  • Operator Precedence
  • PHP Arithmetic Operators
  • Assignment Operators
  • PHP Bitwise Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators

Conditional Operators

  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator
  • Elvis Operator
  • Null Coalescing Operator
  • PHP Data Types
  • PHP Type Juggling
  • PHP Type Casting
  • PHP strict_types
  • Type Hinting
  • PHP Boolean Type
  • PHP Iterable
  • PHP Resource
  • Associative Arrays
  • Multidimensional Array
  • Programming
  • PHP Tutorial

Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions.

Ternary Operator Syntax

The null coalescing operator (), the null coalescing assignment operator (=), the elvis operator (:), wrapping up.

In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable.

Let’s begin with the ternary operator.

The Conditional Operator in PHP, also known as the Ternary Operator, assigns values to variables based on a certain condition. It takes three operands: the condition, the value to be assigned if the condition is true, and the value to be assigned if the condition is false.

Here’s an example:

In this example, the condition is  $score >= 60 . If this condition is true, the value of  $result  is “Pass”. Otherwise, the value of  $result  is “Fail”.

To learn more, visit the  PHP ternary operator tutorial . Let’s now explore the section below to delve into the Null Coalescing Operator in PHP.

The Null Coalescing Operator, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

So, In this example, if the  $_GET['name']  variable is null, the value of  $name  is “Guest”. Otherwise, the value of  $name  is the value of  $_GET['name'] .

Here’s another pattern utilizing it with the assignment operator. Let’s proceed.

The  Null Coalescing Operator  with Assignment, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

So, the value of  $name  is null. The Null Coalescing Assignment Operator assigns the value “Guest” to $name. Therefore, the output of the echo statement is “Welcome,”Guest!”.

Moving into the following section, you’ll learn how to use the Elvis operator in PHP.

In another hand, The  Elvis Operator  is a shorthand version of the Ternary Operator. Which assigns a default value to a variable if it is null. It takes two operands: the variable and the default value to be assigned if the variable is null. Here’s an example:

In this example, if the  $_GET['name']  variable is null, the value“Guest” $name s “Guest”. Otherwise, the value of  $name  is the value of  $_GET['name'] .

Let’s summarize it.

The Conditional Assignment Operators in PHP provide developers with powerful tools to simplify code and make it more readable. You can use these operators to assign values to variables based on certain conditions, assign default values to variables if they are null, and perform shorthand versions of conditional statements. By using these operators, developers can write more efficient and elegant code.

Did you find this tutorial useful?

Your feedback helps us improve our tutorials.

PHP Variable Assignment Within If Statement

The usual practice when checking for the return value of functions is to run the function and store the value in a variable, and then test that variable. Here is an example of that process using the strstr() function.

There is another way to write the same code within a single if statement. The following example assigns the variable and checks the return value in a single line of code.

There is one problem with assigning variables in this way, and this is that you can only do one. If you try to assign more than one variable at a time you will find that everything but the final variable will turn out to be the outcome of the boolean comparison. Take the following example, which uses the same $string variable as the other examples.

The first two comparisons come out as true and so $var1 and $var2 are assigned boolean values of true. The final comparison is the only one that is assigned the expected value. This might be a bug in PHP, but as this is a non-standard way of assigning variables I don't think many people have come across it.

Submitted by James Bower on Mon, 09/07/2009 - 21:17

Submitted by Mirek Suk on Tue, 09/28/2010 - 12:08

Name Philip Norton

Submitted by giHlZp8M8D on Wed, 09/29/2010 - 08:56

Submitted by Jim on Sun, 11/07/2010 - 23:09

This works too: if( !($val = $arg) ) { $val = 'default'; }

Submitted by Frank on Mon, 05/02/2011 - 17:52

Submitted by Vishal on Sun, 05/17/2015 - 09:24

Submitted by Jesus on Tue, 03/20/2018 - 14:55

Submitted by giHlZp8M8D on Tue, 03/20/2018 - 15:19

Submitted by Russ on Fri, 05/31/2019 - 18:18

Submitted by Sam on Fri, 05/15/2020 - 21:30

For fixed payment types, you may be better off to assign an array with the options, with the code as key, and display name as value. That array could be filled from a database query on payment types allowed, which would then pick up when you add a new option, you don't then have to re-code so much.

Submitted by Peter H on Fri, 06/05/2020 - 12:24

Add new comment

Related content, generating colour palettes from images in php.

The main issue in designing a page around the image is that the colours of the page must match the image. Otherwise this creates a dissonance between the image and the styles of the site.

Validating XML Files With XML Schema Definitions In PHP

Creating a character bitmap in php, approximating pi using a circle and a square.

Pi day was a few weeks ago, but I came across this simple approximation of pi recently and decided to put together an example in PHP since it seemed pretty simple.

Drawing A Parabolic Curve With Straight Lines In PHP

Recreating spotify wrapped in php.

I quite like the end of the year report from Spotify that they call "Wrapped". This is a little application in which they tell you what your favorite artist was and what sort of genres you listened to the most during the year.

  • Language Reference
  • Control Structures

elseif/else if

(PHP 4, PHP 5, PHP 7, PHP 8)

elseif , as its name suggests, is a combination of if and else . Like else , it extends an if statement to execute a different statement in case the original if expression evaluates to false . However, unlike else , it will execute that alternative expression only if the elseif conditional expression evaluates to true . For example, the following code would display a is bigger than b , a equal to b or a is smaller than b : <?php if ( $a > $b ) { echo "a is bigger than b" ; } elseif ( $a == $b ) { echo "a is equal to b" ; } else { echo "a is smaller than b" ; } ?>

There may be several elseif s within the same if statement. The first elseif expression (if any) that evaluates to true would be executed. In PHP, it's possible to write else if (in two words) and the behavior would be identical to the one of elseif (in a single word). The syntactic meaning is slightly different (the same behavior as C) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to false , and the current elseif expression evaluated to true .

Note : Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define if / elseif conditions, the use of elseif in a single word becomes necessary. PHP will fail with a parse error if else if is split into two words.

<?php /* Incorrect Method: */ if ( $a > $b ): echo $a . " is greater than " . $b ; else if ( $a == $b ): // Will not compile. echo "The above line causes a parse error." ; endif; /* Correct Method: */ if ( $a > $b ): echo $a . " is greater than " . $b ; elseif ( $a == $b ): // Note the combination of the words. echo $a . " equals " . $b ; else: echo $a . " is neither greater than or equal to " . $b ; endif; ?>

Improve This Page

User contributed notes.

To Top

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Set variable in if statement expression

I ran across some interesting code today. I tried to find out if this is a feature of PHP or if I am missing something, but was unable to find anything on Google. Probably because I don't know the name of it.

The variable $logo is not being set anywhere else. It seems like the expression in this if statement is checking to see if the that class method is returning anything and simultaneously setting the variable $logo to be used in the statement.

Is this true? If so, what in the world is this called!?!

  • if-statement

Chris Bier's user avatar

  • 2 first it assigns, then evaluates the return value of the assignment which is the assigned result. –  bwoebi Commented Apr 18, 2013 at 20:49

2 Answers 2

You can make an assignment like that in a conditional. What happened logically is that the value is assigned to $logo and then $logo is evaluated as to whether it is truthy. If it is truthy, the code in the conditional executes.

You will oftentimes see this sort of assignment/evaluation in the case of looping through database result sets, but generally I would suggest that it should be avoided outside such a common use case for sake of clarity in reading g code.

Mike Brant's user avatar

  • That's what I thought, but I can't seem to find any official documentation on it. Is there a name for it? I want to read the docs about it. –  Chris Bier Commented Apr 18, 2013 at 20:49
  • 2 @ChrisB: It's just how the assignment operator works. It returns the assigned value. Docs: php.net/manual/en/language.operators.assignment.php –  gen_Eric Commented Apr 18, 2013 at 20:51
  • @RocketHazmat I guess I just didn't know you could do that inside of an if statement's expression –  Chris Bier Commented Apr 18, 2013 at 20:52
  • @ChrisB: The = is just an operator, like + or * . It can be used it lots of places :-) –  gen_Eric Commented Apr 18, 2013 at 20:53
  • 2 @ChrisB Generally, use of the assignment operator in a conditional like this should be frowned upon (IMO at least). There are however the handful of cases like looping through a result set of unknown length where it makes sense for example something like: while($row = $db_result->fetch(){ ... } . But in this case my preference would have been to put the assignment on a separate line of code before the conditional. I think this code is more readable and less error prone that way. –  Mike Brant Commented Apr 18, 2013 at 20:56

Yes, this is a feature. It's like:

But in this case, imagine the bool result of if as var $a.

However, IDE's are used to complain about solutions like this because of == vs. = as a very common possible bug source.

Dodo's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged php if-statement or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Is "my death" a/the telos of human life?
  • "There is a bra for every ket, but there is not a ket for every bra"
  • Was Willy Wonka correct when he accused Charlie of stealing Fizzy Lifting Drinks?
  • How to Place a Smooth "Breathing" Above the E with Textgreek?
  • How to deal with coauthors who just do a lot of unnecessary work and exploration to be seen as hard-working and grab authorship?
  • What are the pros and cons of the classic portfolio by Wealthfront?
  • How did people know that the war against the mimics was over?
  • O(nloglogn) Sorting Algorithm?
  • Drill perpendicular hole through thick lumber using handheld drill
  • In QGIS 3, changing borders of shared polygon shapefile features
  • What prevents indoor climbing gyms from making a v18 boulder even if one hasn't been found outside?
  • Definition of annuity
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • How to best characterize the doctrine deriving from Palsgraf?
  • Taylor Swift - Use of "them" in her text "she fights for the rights and causes I believe need a warrior to champion them"
  • Is it a correct rendering of Acts 1,24 when the New World Translation puts in „Jehovah“ instead of Lord?
  • Why does a capacitor act as an open circuit under a DC circuit?
  • Does carbon fiber wings need wing spar?
  • Navigating career options after a disastrous PhD performance and a disappointed advisor?
  • Is it defamatory to publish nonsense under somebody else's name?
  • Custom PCB with Esp32-S3 isn't recognised by Device Manager for every board ordered
  • Is downsampling a valid approach to compare regression results across groups with different sample sizes? If so, how?
  • In Photoshop, when saving as PNG, why is the size of my output file bigger when I have more invisible layers in the original file?
  • Are there something like standard documents for 8.3 filename which explicitly mention about the folder names?

php if with assignment

IMAGES

  1. PHP if Statement

    php if with assignment

  2. PHP Assignment Operators

    php if with assignment

  3. How to Use If Statements in PHP

    php if with assignment

  4. PHP Assignment Operators

    php if with assignment

  5. php tutorial

    php if with assignment

  6. if else Statement in PHP

    php if with assignment

VIDEO

  1. Daily Vlog 24/100 CRUD PHP assignment from IDN Polytechnic

  2. PHP Assignment/Project 4

  3. PHP ASSIGNMENT BAKI HAI LEKIN GAME JARURI HAI

  4. PHP Assignment-3

  5. asst2

  6. php operators, assignment operators

COMMENTS

  1. PHP

    Not least because it's a common newbie mistake to forget that assignment and equality operators are different, so it can easily lead to confusion or difficult-to-detect bugs. ... PHP: Assign multiple variables in if statement. 1. Assign and use variable inside of PHP if statement. Hot Network Questions Bathroom fan venting options

  2. PHP: if

    if. ¶. The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C: statement. As described in the section about expressions, expression is evaluated to its Boolean value.

  3. PHP: Assignment

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. Downloads; ... An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

  4. An Essential Guide to PHP if Statement with Best Practices

    The if statement allows you to execute a statement if an expression evaluates to true. The following shows the syntax of the if statement: statement; Code language: HTML, XML (xml) In this syntax, PHP evaluates the expression first. If the expression evaluates to true, PHP executes the statement. In case the expression evaluates to false, PHP ...

  5. PHP if Statements

    PHP Conditional Statements. Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - executes some code if one condition is true

  6. PHP Conditional Operator: Examples and Tips

    Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions. In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable. Let's begin with the ternary operator. Ternary Operator Syntax

  7. PHP Variable Assignment Within If Statement

    PHP Variable Assignment Within If Statement. Note: This post is over two years old and so the information contained here might be out of date. If you do spot something please leave a comment and we will endeavour to correct. ... This might be a bug in PHP, but as this is a non-standard way of assigning variables I don't think many people have ...

  8. How To Write Conditional Statements in PHP

    Decisions written in code are formed using conditionals: "If x, then y.". Even a button click is a form of condition: "If this button is clicked, go to a certain page.". Conditional statements are part of the logic, decision making, or flow control of a computer program. You can compare a conditional statement to a "Choose Your Own ...

  9. assigning values to a variable in if condition in php

    That's simply not a real question and there is no point in trying to answer it directly, especially if you aren't familiar with PHP syntax.. It's the OP's premises have to be questioned, not the code he's posted.. This code will plainly output the result of getClientAccount method (unless it's 0 or empty array).. So, the OP have to check what "was in the code actually" once more or verify the ...

  10. PHP: elseif/else if

    elseif/else if. ¶. (PHP 4, PHP 5, PHP 7, PHP 8) elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to false. However, unlike else, it will execute that alternative expression only if the elseif conditional expression ...

  11. Bridgeport man killed in Spring Street drive-by shooting ...

    Jessica was previously employed at The Connecticut Mirror as a general assignment reporter. Jessica graduated with her BA in journalism at Central Connecticut State University in May 2023. Jessica ...

  12. PHP: If Else condition assign to variable and call into string

    This may be simple and silly question but first I am learning php so your help would be appreciated. I am trying to get variable with assigned conditional statement.

  13. php

    In the last case, it is important to wrap assignment statement in parenthesis because ! is then used to check against the result of that. Share Improve this answer

  14. PHP If Statement with Multiple Conditions

    It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.

  15. Assign and use variable inside of PHP if statement

    PHP Assign a value to a var from IF statement variable. 5. php variable assignment inside if conditional. 0. Passing a variable inside an if statement PHP. 3. Assign variable whilst checking it. 24. Set variable in if statement expression. 9. Assign variable within condition if true. 1.

  16. php

    Do you notice that PHP sometimes treat assignment before comparison although comparison is higher-precedence and thus should always be performed before assignment?. Any explanations about this? My second question is: should this be avoided by always splitting up this kind of expression? UPDATE. N.B

  17. php

    PHP Assign a value to a var from IF statement variable. 5. php variable assignment inside if conditional. 1. php variable as conditional assignment. 3. Assign variable whilst checking it. 9. Assign variable within condition if true. 2. Setting a variable's value according to the existence of two or more variables. 0.

  18. PHP: Assign multiple variables in if statement

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  19. Using AND/OR in if else PHP statement

    In php both AND, && and OR, || will work in the same way. If you are new in programming and php is one of your first languages them i suggest using AND and OR, because it increases readability and reduces confusion when you check back.

  20. php

    PHP Assign a value to a var from IF statement variable. 5. php variable assignment inside if conditional. 2. If-statement in a Variable. 1. unable to set a variable's value inside an if block in PHP. 0. Passing a variable inside an if statement PHP. 1. Using variables in if statements. 0.