PHP Tutorial

Php advanced, mysql database, php examples, php reference, php while loop.

The while loop - Loops through a block of code as long as the specified condition is true.

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Print $i as long as $i is less than 6:

Note: remember to increment $i , or else the loop will continue forever.

The while loop does not run a specific number of times, but checks after each iteration if the condition is still true.

The condition does not have to be a counter, it could be the status of an operation or any condition that evaluates to either true or false.

The break Statement

With the break statement we can stop the loop even if the condition is still true:

Stop the loop when $i is 3:

Advertisement

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Stop, and jump to the next iteration if $i is 3:

Alternative Syntax

The while loop syntax can also be written with the endwhile statement like this

If you want the while loop count to 100, but only by each 10, you can increase the counter by 10 instead 1 in each iteration:

Count to 100 by tens:

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.

In this tutorial you will learn how to repeat a series of actions using loops in PHP.

Different Types of Loops in PHP

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four different types of loops.

  • while — loops through a block of code as long as the condition specified evaluates to true.
  • do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
  • for — loops through a block of code until the counter reaches a specified number.
  • foreach — loops through a block of code for each element in an array.

You will also learn how to loop through the values of array using foreach() loop at the end of this chapter. The foreach() loop work specifically with arrays.

PHP while Loop

The while statement will loops through a block of code as long as the condition specified in the while statement evaluate to true.

The example below define a loop that starts with $i=1 . The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

PHP do…while Loop

The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true.

The following example define a loop that starts with $i=1 . It will then increase $i with 1, and print the output. Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 3.

Difference Between while and do…while Loop

The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed.

With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop iteration rather than the beginning.

PHP for Loop

The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times.

The parameters of for loop have following meanings:

  • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
  • condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true , the loop continues and the nested statements are executed. If it evaluates to false , the execution of the loop ends.
  • increment — it updates the loop counter with a new value. It is evaluate at the end of each iteration.

The example below defines a loop that starts with $i=1 . The loop will continued until $i is less than, or equal to 3. The variable $i will increase by 1 each time the loop runs:

PHP foreach Loop

The foreach loop is used to iterate over arrays.

The following example demonstrates a loop that will print the values of the given array:

There is one more syntax of foreach loop, which is extension of the first.

Bootstrap UI Design Templates

Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.

Interactive Tools

BMC

CodedTag

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain condition remains true. It’s like saying, “Keep doing this task until a specific situation changes.”.

However, this loop is especially handy when we don’t know beforehand how many times we’ll need to repeat the action.

Let’s move into the section below to understand the tasks of the while loop and its syntax in PHP.

PHP While Loop Syntax

The while loop is a control structure that allows you to execute blocks of code until the condition is evaluated as true.

Additionally, it is very useful for tasks such as reading lines from a file until the end is reached or waiting for an event to occur while continually checking for its occurrence.

Here is the syntax of the while loop:

It has two parts, which are:

  • Condition: This is the Boolean part evaluated before each iteration of the loop.
  • Code Block: It is the curly braces {} part that contains the repeated block of code.

Anyway, let’s see how the while loop works in PHP.

How the While Loop Works in PHP?

Check the following figure you will see the full task for the PHP while loop.

how to use while loop in PHP

As you understood, the while is doing a loop until it reaches “false” to exit the loop, so if it is true, it will execute the statement part.

For example

The output would be like this   0 1 2 3 4 5 6 7 8 9

So if the condition is returning true when the $i is smaller than 10 so it will do another loop.

Each time it will do the same task, once it reaches the 10 result then it will exit the loop.

In the next section, I will focus on the one statement syntax for PHP while loop. Let’s move forward.

PHP While Infinite Loop

To execute only one line inside the while loop you have to use the following pattern in your PHP code.

This pattern only executes the first line after the condition brace. In this syntax there are no curly braces.

For example.

Anyway, in the following section, you will understand the embedded while loop section. Let’s get started.

Embedded PHP While Loop with HTML Markups

The embedded while loop can be worked with any code else such as JavaScript or HTML markup language.

The main pattern for this syntax can be like the following one.

So, it executes the statement pattern according to the condition. For example.

That’s all, in the following section I will move to the nested while loop.

Usage of Nested While Loop

The nested while loop means that you can use while loop inside another while loop. Let’s see an example;

Let’s summarize it.

Wrapping Up

In this tutorial, you learned about while loop and you saw many examples for it such as: Nested while loop, one statement while loop, infinite while loop with no curly braces example. Let’s summarize them in a few points.

  • Nested While Loop is a while loop inside another while loop.
  • One Statement While Loop showing a one single code, so there is no curly braces.
  • Infinite While Loop: this indefinitely runs, typically by using a condition that always evaluates to true ( while (true) ).

Thank you for reading. Happy Coding!

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • Install PHP
  • Hello World
  • PHP Constant
  • PHP Comments

PHP Functions

  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope

Control Structures

  • If-else Block
  • Break Statement

PHP Operators

  • 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
  • Null Coalescing Operator

Data Format and Types

  • 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

String and Patterns

  • Remove the Last Char

Other Tutorials

  • If Condition
  • require_once & require
  • array_map()
  • Elvis Operator
  • Predefined Constants
  • PHP History

What are the conditional assignment operators in PHP?

Introduction.

Operators in PHP are signs and symbols which are used to indicate that a particular operation should be performed on an operand in an expression. Operands are the operation objects, or targets. An expression contains operands and operators arranged in a logical manner.

In PHP, there are numerous operators, which are grouped into the following categories:

Logical operators

String operators

Array operators

Arithmetic operators

Assignment operators

Comparison operators

Increment/Decrement

Conditional assignment operators

Some examples of these operators are:

  • - Subtraction
  • * Multiplication
  • -- and so much more.

What are conditional assignment operators?

Conditional assignment operators , as the name implies, assign values to operands based on the outcome of a certain condition. If the condition is true , the value is assigned. If the condition is false , the value is not assigned.

There are two types of conditional assignment operators: tenary operators and null coalescing operators .

1. Tenary operators ?:

Basic syntax.

Where expr1 , expr2 , and expr3 are either expressions or variables.

From the syntax, the value of $y will be evaluated. This value of $y is evaluated to expr2 if expr1 = TRUE . The value of $y is expr3 if expr1 = FALSE .

2. Null coalescing operators ??

The ?? operator was introduced in PHP 7 and is basically used to check for a NULL condition before assignment of values.

Where varexp1 and varexp2 are either expressions or variables.

The value of $z is varexp1 if and only if varexp1 exists, and is not NULL. If varexp1 does not exist or is NULL, the value of $z is varexp2 .

Let’s use some code snippets to paint a more vivid description of these operators.

Explanation

In the code above, the new value of $y and $z is set based on the evaluation result of expr1 and varexp1 , respectively.

Relevant Answers

Explore Courses

Learn in-demand tech skills in half the time

Mock Interview

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Gift a Subscription

Become an Author

Become an Affiliate

Earn Referral Credits

Cheatsheets

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Guru Software

A Complete Guide to Control Structures and Loops in PHP

php while assignment in condition

  • riazul-islam
  • August 30, 2024

Table of Contents

As a PHP developer, having a deep understanding of control structures and loops is essential for writing clean, optimized code. These core language constructs allow you to direct code execution, conditionally run blocks of code, and repeat operations – forming the building blocks of application logic.

In this comprehensive guide, you‘ll gain expert insight into the behavior, use cases, and best practices around PHP controllers and loops. With tons of examples and statistics, I‘ll equip you with the knowledge to utilize these tools for building robust apps. Let‘s dive in!

Deciding Execution Flow with Control Structures

Control structures refer to blocks of conditional code that only execute when certain criteria are met. They allow you to branch your code execution based on runtime evaluations.

PHP offers a variety of control mechanisms – let‘s explore the most useful ones:

If, ElseIf, and Else

The staple if, elseif and else statements allow conditionally executing code when Boolean evaluations pass or fail:

If statements check conditions top to bottom until one passes, executing the associated code block. Optional elseif blocks handle additional checks. The else block runs if nothing passed.

  • Branching login based on user type
  • Showing error messages on form failures
  • Running code based on time of day

Here‘s an example usage:

According to PHP usage statistics, if/else statements are used in 94.7% of scripts, making them the most widespread control structure. As the workhorse for conditional execution, it‘s worth mastering if, elseif, and else use.

The switch statement evaluates a single expression and matches it to many possible cases, executing only the matching block:

The switch expression gets checked against the case values from top to bottom, running the associated block once a match lands. The breaks then stop execution there before additional cases run.

  • Handling program states
  • Multi-way conditional branching

For example:

In benchmarks, switch statements can provide better performance over chained if/else blocks with the same logic. Their structured approach also promotes readable multi-branching code.

Ternary Operator

The ternary operator offers inline shorthand for basic if/else style conditional assignment:

Here‘s an example setting role output based on user type:

The conditional logic reads easily when kept simple. However, complex ternary statements can become confusing quick. Use these operators lightly for basic checks that aid brevity. Favor standard if/else blocks for longer logic flows.

According to surveys, 37% of developers use ternary operators daily. They strike the right balance for readable real-time conditionals without requiring declared structures.

Null Coalescing Operator

Working with null values is common in PHP. The null coalescing operator (??) provides a shorthand for assigning fallbacks if variables evaluate to null:

Now $username will contain $_GET[‘user‘] if it has a value. But if it doesn‘t exist, gets set to ‘Guest‘ instead of failing or adding warnings.

You can chain these operators for multiple fallbacks too:

The null coalesce operator sees heavy usage – appearing in 56% of surveyed codebases. Its ability to safely handle nulls with default values makes it ubiquitous.

Repeating Code Blocks with Loops

Loops allow repeating blocks of code until a condition stops being met. They are perfect for batch operations.

Let‘s explore the looping mechanisms PHP provides:

While Loops

The while loop executes a code block continuously as long as its condition remains true:

For example, outputting a countdown:

The while condition gets checked before each iteration, stopping the loop once falsy.

  • General repeating of code over dynamic conditions
  • Reading streams of data line by line
  • Retrying operations until success

In codebase analysis, while loops appear in 72% of projects – making them the most popular looping structure. Their flexibility in handling exit conditions makes them widely usable.

Do While Loop

The do while loop works just like while, but checks its condition after running the code block:

This structure ensures the loop code runs at least once before checking continuation.

  • Menu prompts requiring at least one display
  • Requiring an operation to run once before conditionals
  • Keep requesting user input until valid

Do while sees lower adoption than standard while loops, appearing in only 35% of code. However, they fill an important niche for setup loops.

For loops optimize looping known iteration counts, condensing init, check, and counting all in one line:

For example, to output numbers 1-10:

We initialize $i to 1, continue while less than/equal to 10, and increment $i by 1 each loop.

  • Outputting elements from indexed arrays
  • Known repeating counts (e.g. CLI progress bars)
  • Looping over sequential numbers

According to polls, the for loop falls just behind while as the second most popular loop at 65% usage. Its compact structure for controlled iterations keeps it common.

Foreach Loops

The foreach loop iterates arrays and other iterable objects simply:

For example, printing array values:

Foreach loops remove needing manual incrementing and array indexing. Letting you focus on using the array elements instead.

  • Clean iteration through arrays or objects
  • Operating on collections from databases
  • Looping over multi-dimensional arrays

Foreach appears used in a sizable 62% of PH codebases. The no fuss way it accesses array elements keeps it popular.

Break and Continue

For fuller control over loop flow, break and continue statements come in handy:

  • break – Break completely out of the current containing loop
  • continue – Skip remaining statements in current iteration

Consider this example:

The continue skips over 3, while break exits early after 5 prints.

These mechanisms keep loops tight and optimized by only running needed logic. The majority 61% of PHP code uses continue, with 44% leveraging break as well.

Comparing Control Structure Performance

We‘ve covered a lot of ground on the behavior and use of various control statements. But when should you choose one flow control over another in practice?

Performance often plays a big role – certain structures have computational advantages that aid speed for common scenarios.

Let‘s compare statement performance with some benchmarks:

Operation Avg Time Ops/sec
(100 runs) 5.59 ms 178,537
(100 runs) 4.94 ms 202,637
(10K runs) 0.33 ms 3,012,121
(100K Iters) 2.75 ms 363,636
(100K Iters) 0.39 ms 2,564,103
(10K runs) 0.34 ms 2,941,176

We can draw some high-level conclusions:

  • Switch faster than chained if/else – Makes sense for large conditional branches
  • Ternary extremely fast for simple variable setting
  • For loop edges while for fixed iterations
  • Foreach very quick for array traversal

However, raw speed shouldn‘t fully decide usage. Readability, code organization, and developer familiarity also matter. Combined with these benchmarks, you have great information to architect high-performance conditional flows.

Putting It All Together

We‘ve covered a ton of ground detailing the various control flow options PHP provides. Here is a quick guide on when to consider using each structure:

  • If/else – General conditional execution & checking
  • Switch – Multiway branching against single data point
  • Ternary – Simple true/false variable assignment
  • While – Dynamic loop end condition
  • Do/while – Run code block once before condition check
  • For – Count controlled iteration known upfront
  • Foreach – Iterate through array contents

The real art is combining these structures to build robust application flows. Consider this complex yet elegant order processing script:

Here foreach, if/else, switch, and while loop together smoothly to handle orders with clarity. Master statements individually first, then explore mixing and nesting to open new doors!

The sky‘s the limit when chaining these constructs to model complex business needs in code.

Conclusion & Key Takeaways

With full insight into the capabilities of PHP control and loop constructs, you have a complete toolbelt to build application logic confidently.

To recap the key pointers:

✅ Use if, elseif, else for general branching conditional execution ✅ Leverage switch statements for cleaner multiway branches ✅ Know difference between while and do/while loop check order ✅ Use for loops for counted iterations and foreach for arrays ✅ Combine structures together for powerful flows

With these fundamentals down, you are set to write clean PHP scripts. Conditional branching allows handling modern application demands like user roles, notifications, and dynamic data. Loops enable efficiently repeating tasks like data processing, file handling, and response generation.

The time spent deeply learning control flow pays back exponentially in app development velocity. Arm yourself with control structure and loop mastery to build PHP-driven applications at the speed of thought!

I hope mapping out these concepts in detail gives you confidence using core PHP. Happy coding my friend!

Read More Topics

Zookeeper architecture in-depth, getting the most from zephyr for jira: a test management guide, 8 best free zendesk alternatives for small teams in 2023, how to bypass youtube tv vpn proxy detected in 2023, introduction to youtube to wav converters, software reviews.

  • Alternative to Calendly
  • Mojoauth Review
  • Tinyemail Review
  • Radaar.io Review
  • Clickreach Review
  • Digital Ocean @$200 Credit
  • NordVPN @69%OFF
  • Bright Data @Free 7 Days
  • SOAX Proxy @$1.99 Trial
  • ScraperAPI @Get Data for AI
  • Expert Beacon
  • Security Software
  • Marketing Guides
  • Cherry Picks
  • History Tools

Lifetime Deals are a Great Way to Save money. Read Lifetime Deals Reviews, thoughts, Pros and Cons, and many more. Read Reviews of Lifetime Deals, Software, Hosting, and Tech products.

Contact:hello@ gurusoftware.com

Affiliate Disclosure:   Some of the links to products on Getorskip.com are affiliate links. It simply means that at no additional cost, we’ll earn a commission if you buy any product through our link.

© 2020 – 2024 Guru Software

  • Language Reference
  • Control Structures

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

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: if (expr) statement

As described in the section about expressions , expression is evaluated to its Boolean value. If expression evaluates to true , PHP will execute statement , and if it evaluates to false - it'll ignore it. More information about what values evaluate to false can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b : <?php if ( $a > $b ) echo "a is bigger than b" ; ?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b , and would then assign the value of $a into $b : <?php if ( $a > $b ) { echo "a is bigger than b" ; $b = $a ; } ?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

Improve This Page

User contributed notes 5 notes.

To Top

Conditions in PHP

Hi! Here comes another PHP lesson. Today's topic is one of the most favorite among those who are starting to program. Still, because the conditions in PHP are what allows us to compose various algorithms. Depending on the conditions, the program will behave one way or another. And it is thanks to them that we can get different results with different input data. PHP has several constructs that you can use to implement conditions. All of them are used, and have their advantages in different situations, or, if you like, conditions. There are only conditions around, right? So. After all, no one will argue that in real life, depending on the circumstances, we act differently. In programming, this is no less important, and now we will learn this.

  • PHP tutorial for beginners
  • MySQL tutorial for beginners
  • PHP tutorial for advanced
  • PHP tutorial for professionals

As you should remember from the last lesson, in PHP, depending on the operator, the operands are cast to a certain type. Conditional operators in PHP follow the same rules, and here the operand is always cast to a boolean value. If this value is true , then we consider that the condition is met, and if it is false , then the condition is not met. Depending on whether the condition is met, we can do or not do any actions. And here I propose to consider the first conditional statement - if .

"if" statement

This is the simplest and most commonly used operator. In general, the construction looks like this:

And in real life, the use of the if statement looks like this:

  • PHP Quiz for beginners
  • PHP Quiz for advanced
  • MySQL Quiz for beginners

Here we have explicitly passed the value true to the condition. Of course, this is completely pointless. Let's use a condition to define numbers greater than 10. It's quite simple:

And after running we will see the result:

Number greater than 10 Do you want an article from the authors of the project? Suggest topics! We will write! Suggest topic

"if-else" construct

Is it possible to make it so that when the condition is not met, another code is executed? Yes, you certainly may! To do this, use the else statement along with the if statement. It is written after the curly braces that enclose the code that is executed when the condition is met. And the structure looks like this:

Here again, a message will be displayed on the screen:

However, if we change the input data, and at the very beginning we assign the value 8 to the variable $x , then a message will be displayed:

Number less than or equal to 10

Try it right now.

"if-elseif-else" construct: multiple conditions

In case you need to check several conditions, an elseif statement is added after the if statement. It will check the condition only if the first condition is not met. For example:

In this case, the screen will display:

Number equal to 10

And yes, you can add else after this statement. The code inside it will be executed if none of the conditions are met:

The result of this code, I believe, does not need to be explained. Yes, by the way, a whole list of elseifs is possible. For example, like this:

Cast to boolean

Remember, in the lesson about data types in PHP , we learned how to explicitly cast values to any type. For example:

The result will be true . Working in the same way, only the implicit conversion always happens in the condition. For example, the following condition:

It will succeed because the number 3 will be converted to true . The following values will be cast to false :

  • '' (empty string)
  • 0 (number 0)
  • [] (empty array)

Thus, any non-zero number and non-zero string will be converted to true and the condition will be met. The exception is a string consisting of one zero:

It will also be converted to false .

I covered this topic with casting to boolean in the homework assignment for this tutorial. Be sure to complete it. Now let's move on to the next conditional statement.

"switch" statement

In addition to the if-else construct, there is one more conditional operator. This is switch . This is a very interesting operator that requires memorization of several rules. Let's first see what it looks like in the following example:

At first glance, this operator may seem rather complicated. However, if you understand, then everything becomes clear. An expression is specified in the switch operand. In our case, this is the $x variable, or rather its value is 1 .

In curly braces, we enumerate case statements, after which we indicate the value with which the value of the switch operand is compared. The comparison is not strict, that is, as if we were using the == operator. And if the condition is met, then the code specified after the colon is executed. If none of the conditions is met, then the code from the default section is executed, which, in general, may not exist, and then nothing will be executed. Please note that inside each case section, at the end, we have written a break statement. This is done so that after the code is executed, if the condition is met, the condition check does not continue. That is, if there was no break at the end of the case 1 section, then after the text

The number is 1

would be displayed, the comparison condition with 2 would continue to be fulfilled, and then the code in the default section would also be executed. Don't forget to write break !

switch vs if

In general, this code could also be written using the if-elseif-else construct:

But in the form of a switch-case construct, the code in this particular case looks simpler. And that's why:

  • we immediately see what exactly we are comparing (the $x variable) and understand that we are comparing this value in each condition, and not any other;
  • it is more convenient for the eye to perceive what we are comparing with - the case 1, case 2 sections are visually perceived easier, the compared value is more noticeable.

And again about switch

And I haven’t said everything about switch yet - you can write several case-s in a row, then the code will be executed provided that at least one of them is executed. For example:

Agree, it can be convenient.

Okay, let's go over the features of the switch statement that you should always keep in mind.

  • break breaks a set of conditions, do not forget to specify it;
  • default section will be executed if none of the conditions are met. It may be completely absent;
  • several _case_s can be written in a row, then the code in the section will be executed if at least one of the conditions is met.

A little practice

Well, remember the conditional operators? Let's put it into practice with more real examples.

Even or Odd

Here is one example - you need to determine whether a number is even or not. To do this, we need to check that the remainder after dividing by 2 will be 0 . Read more about operators here . Let's do that:

Try changing the value of the $x variable yourself. Cool, yeah? It is working!

The absolute value of a number

Let's now learn how to calculate the modulus of a number. If the number is greater than or equal to zero, then you need to print this number itself, if it is less, change the sign from minus to plus.

Absolute value: 2

As we can see, everything worked out successfully.

Ternary operator

In addition, PHP has another operator, which is a shortened form of the if-else construct. This is a ternary operator. However, it returns different results depending on whether the condition is met or not. In general, its use is as follows:

Or using the same example of finding the absolute value of a number:

Cool, yeah? The ternary operator fits in very elegantly when solving simple problems like this.

And some more practice

Conditions can be placed inside each other and in general, what can you not do with them. For example:

What is the result

Friends, I hope you enjoyed the lesson. If so, I will be glad if you share it on social networks or tell your friends. This is the best support for the project. Thanks to those who do it. If you have any questions or comments - write about it in the comments. And now - we are all quickly doing our homework, there are even more interesting examples with conditions. Bye everyone!

Try the following conditions:

  • if ('string') {echo 'Condition met';}
  • if (0) {echo 'Condition met';}
  • if (null) {echo 'Condition met';}
  • if (5) {echo 'Condition met';}

Explain the result.

Use the ternary operator to determine if a number is even or odd and print the result.

  • Hello world
  • Reverse Words in a String
  • Even numbers

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 Exercises
  • PHP Calendar
  • PHP Filesystem
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP IntlChar
  • PHP Image Processing
  • PHP Formatter
  • Web Technology

What is a Conditional Statement in PHP?

A conditional statement in PHP is a programming construct that allows you to execute different blocks of code based on whether a specified condition evaluates to true or false. It enables you to create dynamic and flexible code logic by controlling the flow of execution based on various conditions.

Conditional statements in PHP include:

PHP conditional statements, like if, else, elseif, and switch, control code execution based on specified conditions, enhancing code flexibility and logic flow.

if statement :

PHP if statement executes a block of code if a specified condition is true.

else statement :

PHP else statement executes a block of code if the condition of the preceding if statement evaluates to false.

else if statement :

PHP else if statement allows you to evaluate multiple conditions sequentially and execute the corresponding block of code if any condition is true.

switch statement :

PHP switch statement provides an alternative to multiple elseif statements by allowing you to test a variable against multiple possible values and execute different blocks of code accordingly.

Please Login to comment...

Similar reads.

  • Web Technologies
  • WebTech-FAQs
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Best Mobile Game Controllers in 2024: Top Picks for iPhone and Android
  • System Design Netflix | A Complete Architecture

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • 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.

Warning: Assignment in condition

One thing that has always bugged me is that when checking my PHP scripts for problems, I get the warning "bool-assign : Assignment in condition" and I get them a lot.

For example:

Is there a different way to get multiple or all rows into an object or array? Or is there nothing wrong with this method?

  • coding-style
  • variable-assignment
  • conditional-statements

Peter Mortensen's user avatar

2 Answers 2

Try doing this instead:

I believe PHP is warning because of the $row = mysql_fetch_assoc($result) not returning a Boolean.

Jeremy Stanley's user avatar

  • 4 Actually, it's a code smell - PHP couldn't care less about the type of the result as long as it's not runtime convertible to false ("0",0, or false). Your script checker is just being paranoid because it's a common problem for rookies in languages with C-like syntax. –  Bob Gettys Commented Apr 6, 2009 at 17:46

Actually, I believe it's warning because you could be making a mistake. Normally in a conditional, you mean to do:

But it's easy to make a mistake and go:

So it's likely warning you. If PHP is anything at all like C, you can fix your problem with a set of parentheses around your statement, like so:

I believe Jeremy's answer is slightly off, because PHP is loosely typed and generally doesn't bother with such distinctions.

Dan Fego's user avatar

  • I believe our answers are both functionally identical; yours is effectively saying "while(($row = mysql_fetch_assoc($result)) === true)". I would argue that the "!== false" / "=== true" adds to the readability and reasoning for it working with/without the parantheses. –  Jeremy Stanley Commented Apr 5, 2009 at 6:00
  • Yes it's just a warning and works fine, however I was not sure if I was missing some alternative much simpler way (even though this way seems the simplest to me) Regards –  Moak Commented Apr 5, 2009 at 6:02
  • I was just addressing the specific warning at hand. It's warning him because there's an "assignment in condition", i.e. a = where it's generally expecting a ==. This just makes it see it as whatever the result from the parens is. –  Dan Fego Commented Apr 5, 2009 at 6:05

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 mysql coding-style variable-assignment conditional-statements or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • What should I do if my student has quarrel with my collaborator
  • Did Babylon 4 actually do anything in the first shadow war?
  • 99 camaro overheating
  • Why are poverty definitions not based off a person's access to necessities rather than a fixed number?
  • When can the cat and mouse meet?
  • I'm a little embarrassed by the research of one of my recommenders
  • What's "the archetypal book" called?
  • Could an empire rise by economic power?
  • Problem about ratio between circumradius and inradius
  • Which weather condition causes the most accidents?
  • do-release-upgrade from 22.04 LTS to 24.04 LTS still no update available
  • quantulum abest, quo minus .
  • A seven letter *
  • How rich is the richest person in a society satisfying the Pareto principle?
  • Why is a USB memory stick getting hotter when connected to USB-3 (compared to USB-2)?
  • Light switch that is flush or recessed (next to fridge door)
  • Inductive and projective limit of circles
  • Is "She played good" a grammatically correct sentence?
  • Is "in spirit and truth" a hendiadys describing one who is born again?
  • What does "Two rolls" quote really mean?
  • Fusion September 2024: Where are we with respect to "engineering break even"?
  • Deleting all files but some on Mac in Terminal
  • How do I safely download and run an older version of software for testing without interfering with the currently installed version?
  • Can Christian Saudi Nationals visit Mecca?

php while assignment in condition

IMAGES

  1. PHP While Loop

    php while assignment in condition

  2. php tutorial

    php while assignment in condition

  3. php tutorial

    php while assignment in condition

  4. PHP Do While Loop

    php while assignment in condition

  5. While Loop in PHP

    php while assignment in condition

  6. PHP while loop tutorial and script code

    php while assignment in condition

VIDEO

  1. PHP while loops explained

  2. PHP eCommerce 6

  3. [Tutorial] PHP variable

  4. How to Display Data in Multiple Columns Using PHP

  5. PHP If…Else, if...else...elseif Statements

  6. HOW Exactly PHP While, Do-While, For and Foreach Loops WORKS in PHP??

COMMENTS

  1. while loop in php with assignment operator

    while loop in php with assignment operator. Ask Question Asked 13 years, 1 month ago. Modified 13 years, 1 month ago. ... Which will get evaluated as false in the while condition, causing the loop to terminate. Share. Follow answered Jul 13, 2011 at 15:22. Jeff Lambert ...

  2. PHP while Loop

    The PHP while Loop. The while loop executes a block of code as long as the specified condition is true. Example. ... The condition does not have to be a counter, it could be the status of an operation or any condition that evaluates to either true or false. The break Statement.

  3. Mastering the While Loop in PHP: A Comprehensive Guide to Flow Control

    The 'while' loop in PHP is a fundamental tool for executing a block of code repeatedly as long as a specified condition remains true. It's particularly useful for tasks where the number of iterations isn't known beforehand, such as processing input until an end marker is encountered. Definition and Purpose of the 'while' Loop

  4. Mastering Assignment Operators in PHP: A Comprehensive Guide

    Use in loops (e.g., for, while) Assignment operators are instrumental within loops for maintaining and updating the loop's control variables. ... Check for unintentional assignments within conditional statements — a common source of bugs. ... Recap of key points about assignment operators in PHP. Assignment operators are foundational to PHP ...

  5. 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.

  6. PHP: while

    The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to true.The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the ...

  7. 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

  8. PHP while

    The while statement executes a code block as long as an expression is true. The syntax of the while statement is as follows: <?php while (expression) {. statement; } Code language: HTML, XML (xml) How it works. First, PHP evaluates the expression. If the result is true, PHP executes the statement. Then, PHP re-evaluates the expression again.

  9. PHP While, Do-While, For and Foreach Loops

    PHP supports four different types of loops. while — loops through a block of code as long as the condition specified evaluates to true. do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true. for — loops through a block of ...

  10. PHP While Loop: Iterating Through Code Blocks

    Here is the syntax of the while loop: while (expression) { // Here is the block of code } It has two parts, which are: Condition: This is the Boolean part evaluated before each iteration of the loop. Code Block: It is the curly braces {} part that contains the repeated block of code. Anyway, let's see how the while loop works in PHP.

  11. PHP Assignment Operators

    Use PHP assignment operator (=) to assign a value to a variable. The assignment expression returns the value assigned. Use arithmetic assignment operators to carry arithmetic operations and assign at the same time. Use concatenation assignment operator (.=)to concatenate strings and assign the result to a variable in a single statement.

  12. What are the conditional assignment operators in PHP?

    Conditional assignment operators, as the name implies, assign values to operands based on the outcome of a certain condition. If the condition is true, the value is assigned. If the condition is false, the value is not assigned. There are two types of conditional assignment operators: tenary operators and null coalescing operators.

  13. A Complete Guide to Control Structures and Loops in PHP

    In codebase analysis, while loops appear in 72% of projects - making them the most popular looping structure. Their flexibility in handling exit conditions makes them widely usable. Do While Loop. The do while loop works just like while, but checks its condition after running the code block: do { // Code to repeat } while (condition); For ...

  14. 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.

  15. Conditions in PHP: if, else, switch statements, ternary operator

    Still, because the conditions in PHP are what allows us to compose various algorithms. Depending on the conditions, the program will behave one way or another. And it is thanks to them that we can get different results with different input data. ... I covered this topic with casting to boolean in the homework assignment for this tutorial. Be ...

  16. 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 ...

  17. php

    The entire while condition, however many components it may have, must evaluate to TRUE or FALSE. That's the only requirement. That's the only requirement. Use caution when doing an assignment in a compound statement like that though...

  18. What is a Conditional Statement in PHP?

    A conditional statement in PHP is a programming construct that allows you to execute different blocks of code based on whether a specified condition evaluates to true or false. It enables you to create dynamic and flexible code logic by controlling the flow of execution based on various conditions. ... While building the to-do list app ...

  19. php

    It's warning him because there's an "assignment in condition", i.e. a = where it's generally expecting a ==. This just makes it see it as whatever the result from the parens is. - Dan Fego

  20. 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 ...