Home » PHP Tutorial » PHP Ternary Operator

PHP Ternary Operator

Summary : in this tutorial, you will learn to use the PHP ternary operator to make the code shorter and more readable.

Introduction to the PHP ternary operator

The ternary operator is a shorthand for the if...else statement. Instead of writing this:

you can use this:

How it works.

  • First. PHP evaluates the condition . If it’s true, the right-hand expression returns the value1 ; otherwise, it returns the value2 .
  • Second, PHP assigns the result of the right-hand expression to the $result variable.

As you can see, by using the ternary operator, you can make the code more concise.

Note that the name ternary operator comes from the fact that this operator requires three operands: expression , value1 , value2 .

PHP ternary operator example

Suppose you want to display the login link if the user has not logged in and the logout link if the user has already logged in. To do that, you can use the if...else statement as follows:

In this example, the $title will be 'Login' because the $is_user_logged_in is set to false . The code is quite lengthy. And you can make it shorter by using the ternary operator as follows:

It’s much shorter now. If the line is long, you can always break it down like this:

The shorthand ternary operator

Starting from PHP 5.3, you can use the shorthand ternary operator as follows:

In this syntax, PHP evaluates $initial in the boolean context. If $initial is true, PHP assigns the value of the $initial to the $result variable. Otherwise, it assigns the $default to the $result variable.

The following example uses the shorthand ternary operator to assign the value of the $path to the $url if the $path is not empty. If the $path is empty, the ternary operator assigns the literal string ‘/’ to the $url :

Chaining ternary operators

Technically, you can chain ternary operators by using parentheses.

Suppose you want to show various messages if users are eligible and have enough credit. The following example chains two ternary operators:

Most of the time, chaining multiple ternary operators makes the code more difficult to read. In this case, it’s better to use if...else or if...elseif statement.

  • The ternary operator ( ?: ) is a shorthand for the if...else statement.
  • Do use the ternary operator when it makes your code more concise and more readable.
  • PHP Tutorial
  • PHP Calendar
  • PHP Filesystem
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP IntlChar
  • PHP Image Processing
  • PHP Formatter
  • Web Technology
  • PHP Introduction
  • How to install PHP in windows 10 ?
  • How to Install PHP on Linux?
  • PHP | Basic Syntax
  • How to write comments in PHP ?
  • PHP | Variables
  • PHP echo and print
  • PHP | Data Types
  • PHP | Strings
  • Associative Arrays in PHP
  • Multidimensional arrays in PHP
  • Sorting Arrays in PHP 5

PHP Constants

  • PHP | Constants
  • PHP Constant Class
  • PHP Defining Constants
  • PHP | Magic Constants
  • PHP Operators
  • PHP | Bitwise Operators

PHP | Ternary Operator

Php control statements.

  • PHP | Decision Making
  • PHP switch Statement
  • PHP break (Single and Nested Loops)
  • PHP continue Statement
  • PHP | Loops
  • PHP while Loop
  • PHP do-while Loop
  • PHP for Loop
  • PHP | foreach Loop

PHP Functions

  • PHP | Functions
  • PHP Arrow Functions
  • Anonymous recursive function in PHP

PHP Advanced

  • PHP | Superglobals
  • HTTP GET and POST Methods in PHP
  • PHP | Regular Expressions
  • PHP Form Processing
  • PHP Date and Time
  • Describe PHP Include and Require
  • PHP | Basics of File Handling
  • PHP | Uploading File
  • PHP Cookies
  • PHP | Sessions
  • Implementing callback in PHP
  • PHP | Classes
  • PHP | Constructors and Destructors
  • PHP | Access Specifiers
  • Multiple Inheritance in PHP
  • Abstract Classes in PHP
  • PHP | Interface
  • Static Function in PHP
  • PHP | Namespace

MySQL Database

  • PHP | MySQL Database Introduction
  • PHP | MySQL ( Creating Database )
  • PHP Database connection
  • Connect PHP to MySQL
  • PHP | MySQL ( Creating Table )
  • PHP | Inserting into MySQL database
  • PHP | MySQL Select Query
  • PHP | MySQL Delete Query
  • PHP | MySQL WHERE Clause
  • PHP | MySQL UPDATE Query
  • PHP | MySQL LIMIT Clause

Complete References

  • PHP Array Functions
  • PHP String Functions Complete Reference
  • PHP Math Functions Complete Reference
  • PHP Filesystem Functions Complete Reference
  • PHP intl Functions Complete Reference
  • PHP IntlChar Functions Complete Reference
  • PHP Image Processing and GD Functions Complete Reference
  • PHP Imagick Functions Complete Reference
  • PHP ImagickDraw Functions Complete Reference
  • PHP Gmagick Functions Complete Reference
  • PHP GMP Functions Complete Reference
  • PHP Ds\Set Functions Complete Reference
  • PHP Ds\Map Functions Complete Reference
  • PHP Ds\Stack Functions Complete Reference
  • PHP Ds\Queue Functions Complete Reference
  • PHP Ds\PriorityQueue Functions Complete Reference
  • PHP Ds\Deque Functions Complete Reference
  • PHP Ds\Sequence Functions Complete Reference
  • PHP SPL Data structures Complete Reference
  • PHP Ds\Vector Functions Complete Reference
  • PHP DOM Functions Complete Reference

If-else and Switch cases are used to evaluate conditions and decide the flow of a program. The ternary operator is a shortcut operator used for shortening the conditional statements.

ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right. It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. 

  • Condition: It is the expression to be evaluated and returns a boolean value.
  • Statement 1: It is the statement to be executed if the condition results in a true state.
  • Statement 2: It is the statement to be executed if the condition results in a false state.

The result of this comparison can also be assigned to a variable using the assignment operator. The syntax is as follows:  

If the statement executed depending on the condition returns any value, it will be assigned to the variable.

Advantages of Ternary Operator: Following are some advantages of ternary operator:

  • The use of the ternary operator will make the code shorter in comparison to the IF ELSE statement.
  • The code can be quick in length in comparison to the IF ELSE statement.
  • The readability of the code will increase with the usage of conditional statements.
  • The use of the ternary operator makes the code simpler.

Example 1: In this example, if the value of $a is greater than 15, then 20 will be returned and will be assigned to $b, else 5 will be returned and assigned to $b.

Output:  

Example 2: In this example, if the value of $age is more than or equal to 18, “Adult” is passed to print function and printed, else “Not Adult” is passed and printed.

When we use ternary operator: We use the ternary operator when we need to simplify the if-else statements that are simply assigning values to variables depending on a condition. An advantage of using a ternary operator is that it reduces the huge if-else block to a single line, improving the code readability and simplify it. Very useful while assigning variables after form submission. 

Example:  

Original Code:  

Reduced to the following: Thus, the ternary operator successfully reduces the if-else block to a single line, hence serving its purpose. 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples .

Please Login to comment...

Similar reads.

author

  • Web Technologies
  • Write From Home
  • 10 Best Free Note-Taking Apps for Android - 2024
  • 10 Best VLC Media Player Alternatives in 2024 (Free)
  • 10 Best Free Time Management and Productivity Apps for Android - 2024
  • 10 Best Adobe Illustrator Alternatives in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

PHP Ternary

Switch to English

  • Introduction

Table of Contents

Basic Syntax of PHP Ternary Operator

Example of php ternary operator, tips and tricks, common error-prone cases and how to avoid them.

  • Condition: This is the condition that you want to test.
  • Value_if_true: If the condition is true, then this value is assigned to the variable.
  • Value_if_false: If the condition is false, then this value is assigned to the variable.
  • While the PHP ternary operator can make your code more concise, it can also make it less readable if overused. Therefore, use it sparingly and for simple conditions only.
  • You can also nest ternary operators, but this can make your code even more difficult to read and understand. It's usually better to use if-else statements for complex conditions.
  • One common mistake is to forget the colon (:), which separates the true and false values. This will result in a syntax error. Always remember to include it.
  • Another common mistake is not properly enclosing the condition in parentheses. This can lead to unexpected results, especially with complex conditions. Always enclose the condition in parentheses to ensure that it is evaluated correctly.
  • Python (302)
  • Javascript (658)
  • HTML5 (534)
  • Object-oriented Programming (120)
  • React (280)
  • Node.js (264)
  • Data Structure (172)
  • WordPress (226)
  • jQuery (326)
  • Angular (306)
  • Google Ads (172)
  • Django (253)
  • Digital Marketing (196)
  • TypeScript (288)
  • Redux (268)
  • Kotlin (290)
  • MongoDB (262)
  • Laravel (252)
  • Swift (172)
  • Cloud Computing (286)
  • Agile/Scrum (208)
  • ASP.NET (254)
  • UI/UX Design (170)
  • Analytics (258)
  • Linux (252)
  • Search Engine Optimization (936)
  • Github (240)
  • Bootstrap (264)
  • Machine Learning (237)
  • Project Management (244)
  • REST API (270)
  • Oracle (264)
  • Excel (276)
  • Adobe Photoshop (232)
  • Data Science (235)
  • Artificial Intelligence (262)
  • Vue.js (280)
  • Hadoop (244)
  • GoLang (266)
  • Scala (262)
  • Solidity (252)
  • Ruby on Rails (246)
  • Augmented Reality (218)
  • VidGenesis (1317)
  • Virtual Reality (88)
  • Unreal Engine (78)

Popular Articles

  • Php Remove Last Character From String (Nov 08, 2023)
  • Php Reset (Nov 08, 2023)
  • Php Optional Parameters (Nov 08, 2023)
  • Php Null (Nov 08, 2023)
  • Php Join Array (Nov 08, 2023)
  • 4185 Quilly Lane, Dublin
  • 614-520-2242
  • [email protected]

PHP-compiler

PHP Compiler Conference

How to Use the PHP Ternary Operator

The PHP ternary operator stands as a more compact alternative to the if…else statement, promoting code simplicity and readability. It turns lengthy conditional structures into a manageable, single line of code, contributing to cleaner and more efficient programming.

You may also like: Moving from the PHP Ternary Operator, let’s take a look at the array_filter function in PHP , a practical tool for filtering array elements.

PHP Ternary Operator

The PHP ternary operator offers a succinct alternative to the traditional if…else statement. Here’s a standard if…else construct in PHP:

  • Initially, PHP examines the given condition. Depending on its truthfulness, it either yields value1 (if the condition is true) or value2 (if it’s false);
  • Next, PHP allocates the outcome derived from this evaluation to the variable $result;
  • This demonstrates how the ternary operator simplifies coding by condensing it.

It’s noteworthy that this operator is called ‘ternary’ because it operates with three elements: the condition, value1, and value2.

Illustrating PHP’s Ternary Operator with Examples

Close-up of a person's hands typing code on a laptop

Imagine a scenario where you need to display different links based on the user’s login status. In PHP, a common approach is to use an if…else statement. Here’s an example:

In this case, since $is_user_logged_in is false, $title will be set to ‘Login’. While effective, this method can be verbose. A more succinct alternative is using the ternary operator, as shown below:

This compact form achieves the same result with less code. Furthermore, for longer expressions, the ternary statement can be formatted for clarity:

This method not only makes the code more readable but also maintains its functionality efficiently.

Utilizing the Compact Ternary Operator in PHP

With the release of PHP 5.3, developers have the option to implement the compact ternary operator in this manner:

This operator allows for a concise evaluation in PHP. It checks the $initial variable in a boolean context. If $initial evaluates to true, PHP will assign its value to the $result variable. If not, $default is assigned to $result instead.

An example of using this operator is demonstrated below, where the value of $path is assigned to $url if $path is not null or empty. Should $path be empty, the operator assigns a default string ‘/’ to $url:

This example effectively illustrates the utility of the compact ternary operator in PHP for streamlined code and efficient value assignment.

Implementing Nested Ternary Operators in PHP

Cartoon of a programmer with code and web technology icons

In PHP, it’s possible to nest ternary operators within each other by using parentheses for more complex conditional logic.

Consider a scenario where you need to display different messages based on user eligibility and credit status. Here’s an example where two ternary operators are nested:

While nesting ternary operators is technically feasible, it often leads to code that is harder to read and understand. In such situations, opting for if…else or if…elseif constructs is generally more advisable for clarity and maintainability.

Conclusion 

The ternary operator (?:) serves as a concise alternative to the if…else statement. It is recommended to use this operator when it simplifies and enhances the readability of your code.

CodedTag

  • Ternary Operator

The PHP Ternary Operator is a shorthand syntax for an if-else statement. It provides a concise way to write conditional expressions in a single line of code.

The usage of the ternary operator is frequent when assigning values to variables based on specific conditions.

Let’s take a look at its syntax in PHP.

The Basic Syntax

The basic syntax of the PHP Ternary Operator is:

Here, the condition is the expression that is evaluated. If it is true, the variable is assigned the true_value; otherwise, it is assigned the false_value.

Anyway, the ternary operator is useful for writing compact and readable code when dealing with simple conditional assignments. However, it’s important to use it judiciously and consider readability, as complex ternary expressions can become difficult to understand.

Let’s take an example of how to write shorthand using the ternary operator within PHP.

Using the Shorthand Ternary Operator in PHP

The ternary operator itself is often informally called the shorthand or conditional operator because it provides a compact syntax for expressing conditional statements in a single line. It is commonly used for quick, one-line assignments based on a condition. Here’s a brief example:

In this example, the ternary operator serves as a shorthand way to assign the boolean value true to the variable $isAdult if the condition $age >= 18 is true, and false otherwise. The term “shorthand” reflects the brevity and simplicity that the ternary operator introduces compared to the more verbose if-else statements.

In this way, we just need to understand the difference between the traditional if statement and the ternary operator. Let’s move on to the following section to delve into more details.

Ternary Operator vs. Traditional If-Else Statements in PHP

The Ternary Operator provides a concise way to express the conditional assignment in a single line. However, for more complex conditions or multiple actions, the traditional If-Else Statements may be preferred for better readability and maintainability.

Consequently, the Ternary Operator and traditional If-Else Statements in PHP serve distinct purposes, and their differences can be illustrated through a simple example. Consider checking whether a given number is even or odd.

PHP Ternary Operator:

The condition $number % 2 === 0 is evaluated. If true, 'even' is assigned to the $result variable; otherwise, 'odd' is assigned. The entire operation is condensed into a single line, promoting conciseness and readability for straightforward conditions.

On the other hand, with traditional If-Else Statements :

The condition is checked using the if statement. If true, 'even' is assigned to $result ; otherwise, the else block assigns 'odd' . This approach is more suitable for scenarios with complex conditions or multiple actions, as it allows for a clearer and more structured representation of the logic.

Let’s take a look at another pattern for the PHP ternary operator, specifically the nested ternary operator.

Nested Ternary Operator

Nested ternary operators refer to the use of multiple ternary operators within a single expression. This can lead to concise yet complex conditional logic, but it requires careful consideration of readability. Here’s an example to illustrate nested ternary operators:

In this example:

  • The outer ternary operator checks if $number is even.
  • If true, the inner ternary operator checks if $number is positive.
  • Depending on the conditions, different messages are assigned to the $result variable.

Additionally, you can utilize the ternary operator with short echo tags. Let’s explore how it works through an example.

Ternary Operator in Short Echo Tags in PHP

In PHP, the ternary operator can be utilized within short echo tags ( <?= ... ?> ) to conditionally output values. Short echo tags are a shorthand way of writing an echo statement.

Here’s an example demonstrating the use of the ternary operator within short echo tags:

This results in the output message “Your result: Pass” if the score is 75 or higher, and ‘Your result: Fail’ if the score is below 70.

Let’s summarize it.

Wrapping Up

the PHP Ternary Operator offers a concise syntax for expressing conditional assignments in a single line of code, providing a quick and efficient way to handle simple conditions. While it promotes brevity and readability for straightforward assignments, it’s crucial to use it judiciously, especially for more complex scenarios.

The comparison between the Ternary Operator and traditional If-Else Statements highlights the distinct purposes each serves. The Ternary Operator is suitable for streamlined, one-line assignments, while If-Else Statements are preferable for more intricate conditions or multiple actions, enhancing code readability and maintainability.

The exploration of nested ternary operators introduces a more advanced pattern, emphasizing the importance of carefully balancing conciseness with readability in complex conditional logic.

Additionally, the ability to use the ternary operator within short echo tags provides a convenient way to conditionally output values, streamlining the process of generating dynamic content in PHP.

Thank you for reading. To access more tutorials, please visit here .

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

PHP Ternary Operator

Php tutorial index.

When coding, we always look for shortcuts everywhere or try to make things concise and effective. In PHP and other programming languages, the ternary operator is a concise way to write conditional statements that improve code readability and effectiveness.

You might have read about the "if-else" conditional statement of PHP. The PHP ternary operator is another way to implement this concept with a different technique. Here, three different operations will work in conjunction to make a single operator. In this tutorial, you will learn about the conditional operator.

What Is the Ternary Operator in PHP?

Ternary operators can be defined as a conditional operator that is reasonable for cutting the lines of codes in your program while accomplishing comparisons as well as conditionals. This is treated as an alternative method of implementing if-else or even nested if-else statements . This conditional statement takes its execution from left to right. Using this ternary operator is not only an efficient solution but the best case with a time-saving approach. It returns a warning while encountering any void value in its conditions.

The syntax of using the conditional operator in PHP is:

  • Condition statement : This is a valid PHP expression that will be evaluated in order to return a Boolean value.
  • Statement_1 : This will be the statement that will be executed when the conditional results will return true or be in a true state.
  • Statement_2 : This will be the statement that will be executed when the conditional results will return true or be in a false state.

When to Use Ternary Operator

You can use the ternary operator when there is a need to simplify if-else statements or if the programmer wants to make efficient code out of a complex program structure. Moreover, conditional statements are also used while assigning post data or validate forms within an application.

Advantages of Ternary Operator

  • The code will be short in size as compared to the IF statement.
  • Readability increases with the use of conditional statements.
  • The use of this ternary operator makes the code simpler.

Ternary Shorthand

Shorthand can also be used with this ternary operator by leaving out the ternary operator's central portion. This shorthand operator is also known as Elvis operator, which is written as:

The full syntax can be written:

Mastering Ternary Operator in PHP

Introduction.

The ternary operator in PHP provides a shorthand way of writing conditional statements, allowing for clearer and more concise code. In this tutorial, we’ll explore how to use the ternary operator through a series of examples from simple to complex scenarios.

Basic Usage of Ternary Operator

The ternary operator is a conditional operator that takes three operands. The basic syntax is (condition) ? (expression_if_true) : (expression_if_false) . Here’s a simple example:

This will output You are an adult. since the condition $age >= 18 is true.

Nested Ternary Operators

Nested ternary operators allow for multiple conditions to be checked in a single statement. Care should be taken to ensure readability:

The above code outputs You are an adult. , since the first condition is true, and the nested condition is false.

Using with Functions

The ternary operator can be used to execute different functions based on a condition. For example:

This will output Odd number since the number 5 is odd.

Ternary Operator as a Null Coalescing Operation

PHP 7 introduced the null coalescing operator ?? , but a similar effect can be achieved with the ternary operator by using isset() :

This will output Welcome guest if the username is not provided in the query string, otherwise it outputs the username.

Ternary Operator for Shortening Lengthy If-Else Chains

You can replace lengthy if-else chains with the ternary operator. However, maintaining readability should always be a priority:

With a score of 85, this code will output You got a B .

Advanced Conditional Assignment

In more advanced use-cases, the ternary operator can handle compound conditions and execute corresponding complex expressions:

If login attempts exceed 5, the account is locked. Otherwise, it shows how many attempts are remaining.

Best Practices with Ternary Operator

It’s essential to avoid overusing ternary operators as they can significantly decrease readability. Picking the right scenario to use a ternary operator can greatly improve the clarity and efficiency of your code.

The ternary operator in PHP is a powerful tool for writing concise and readable conditional statements. Throughout this tutorial, we’ve explored its use across various scenarios, illustrating how to effectively use it to streamline your PHP code. Remember that readability should always come first, so use ternary operators wisely.

Next Article: How to upgrade PHP to the latest version in Windows

Previous Article: Using 'never' return type in PHP (PHP 8.1+)

Series: Basic PHP Tutorials

Related Articles

  • Using cursor-based pagination in Laravel + Eloquent
  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js
  • Language Reference

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of " $a = 3 " is 3. This allows you to do some tricky things: <?php $a = ( $b = 4 ) + 5 ; // $a is equal to 9 now, and $b has been set to 4. ?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic , array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: <?php $a = 3 ; $a += 5 ; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello " ; $b .= "There!" ; // sets $b to "Hello There!", just like $b = $b . "There!"; ?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

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.

Assignment by Reference

Assignment by reference is also supported, using the " $var = &$othervar; " syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

The above example will output:

More information on references and their potential uses can be found in the References Explained section of the manual.

Arithmetic Assignment Operators

Bitwise assignment operators, other assignment operators.

  • arithmetic operators
  • bitwise operators
  • null coalescing operator

User Contributed Notes 4 notes

To Top

PHP Tutorial : Beginner's Guide to PHP

How to install php on windows, php frameworks: everything you need to know about php frameworks, how to implement design patterns in php, how to run a php program in xampp, get vs post: what is the difference between get and post method, how to best utilize echo in php, how to implement intval in php, how to decrypt md5 password in php, how to convert object to array in php, everything you need to know about unserialize in php, php tutorial: data types and declaration of variables & strings in php, what is ternary operator in php and how is it used, what is a cookie in php, how to implement abstract class in php, how to best utilize exception handling in php, php error handling: all you need to know, how to implement interface in php, how to remove index.php from url in codeigniter, how to build a regular expression in php, split in php: what is str_split() function, how to best utilize trim function in php, how to write a file in php, top 50 php interview questions you must prepare in 2024, programming & frameworks.

php assign variable ternary

Using the if-else and switch case is an essential part of programming for evaluating conditions. We always look for shortcuts everywhere whether it is a route for traveling or game or code. In this Ternary Operator PHP , we will see how it is used for shortening conditional statements in the following sequence:

What is Ternary operator?

When do we use ternary operator, advantages of ternary operator, ternary shorthand, null coalescing operator.

The ternary operator is a conditional operator that decreases the length of code while performing comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this operator is from left to right. Obviously, it is the best case for a time-saving option.

It also produces an e-notice while encountering a void value with its conditionals. It is called a ternary operator because it takes three operands – a condition, a result for true, and a result for false.

  • Condition: It is the expression to be evaluated which returns a boolean value.
  • Statement 1: it is the statement to be executed if the condition results in a true state.
  • Statement 2: It is the statement to be executed if the condition results in a false state.

Example program to whether student is pass or fail:

We use ternary operator when we need to simplify if-else statements that are used to assign values to variables. Moreover, it is commonly used when we assign post data or validate forms.

Let’s say, we were programming a login form for a college university where we wanted to ensure that the user entered their registration number provided by the university then we could move further.

Let’s look at an example of a validation form for better understanding:

In order to get the values of our text fields, we can use the following code:

  • It will make the code shorter
  • It will make the code more readable
  • The code becomes simpler

Short ternary operator syntax can be used by leaving out the middle part of the ternary operator for quick shorthand evaluation. It is also referred to as Elvis operatory(?:)

Elvis operator can be used in order to reduce redundancy of your conditions and shorten the length of your assignments. It is the ternary operator with the second operand omitted. It will return the first operand if the operand is true else it evaluates and returns its second operand.

If you use the ternary shorthand operator like this, it will cause notice if

is not set, instead of writing some lengthy code like this:

It replaces the ternary operation in conjunction with isset() function which is used to check whether a given variable is NULL or not and returns its first operand if it exists and is not NULL else it returns the second operand.

It will fetch the value of $_GET[‘user’] and returns ‘nobody’ if it does not exist.

Instead of writing some lengthy code like this:

With this we come to an end of this article, I hope you understood the ternary operator, the purpose and advantages of the ternary operator, Ternary shorthand and Null coalescing Operator.

If you found this Ternary Operator blog relevant, check out the PHP Certification Training  by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”ternary operator in php” and I will get back to you.

Recommended videos for you

Portal development and text searching with hibernate, spring framework : introduction to spring web mvc & spring with bigdata, learn perl-the jewel of scripting languages, building application with ruby on rails framework, effective persistence using orm with hibernate, introduction to java/j2ee & soa, service-oriented architecture with java, responsive web app using cakephp, php and mysql : server side scripting for web development, hibernate-the ultimate orm framework, create restful web application with node.js express, ms .net – an intellisense way of web development, rapid development with cakephp, building web application using spring framework, nodejs – communication and round robin way, node js express: steps to create restful web app, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, microsoft .net framework : an intellisense way of web development, mastering regex in perl, recommended blogs for you, factorial program in c: how to calculate factorial of a number, what is association in java and why do you need it, linked list in java: how to implement a linked list in java, what is aggregation in java and why do you need it, how to implement map interface in java, top 50 css interview questions you should prepare for in 2024, how to connect to a database in java – jdbc tutorial, how to implement and play with strings in python, what are the different applications of java, what is a java thread pool and why is it used, java enum tutorial: what is it and how to implement it, top 10 front end developer skills you need to know, ways for swapping two numbers in java, how to set classpath in java, what is jsp in java know all about java web applications, all you need to know about array search in php, what are product management courses why are they crucial, join the discussion cancel reply, trending courses in programming & frameworks, full stack web development internship program.

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Certification Training Course

  • 75k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Flutter Application Development Course

  • 12k Enrolled Learners

Spring Framework Certification Course

Node.js certification training course.

  • 10k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

Microsoft .NET Framework Certification Traini ...

  • 6k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Browse Categories

Subscribe to our newsletter, and get personalized recommendations..

Already have an account? Sign in .

20,00,000 learners love us! Get personalised resources in your inbox.

At least 1 upper-case and 1 lower-case letter

Minimum 8 characters and Maximum 50 characters

We have recieved your contact details.

You will recieve an email from us shortly.

Ternary and Ternary Coalescing Operator in PHP

PHP supports various forms of ternary and coalescing operators. This is a quick post to catch-up to all ternary and coalescing operators supports in PHP.

1. Ternary Operator: cond ? expr1 : expr2

Ternary operator is a short form for an if/else block that executes exactly one expression each.

The if/else block above is quite verbose and consumes more space for a simple expression. With the ternary operator, you can optimize this:

Its syntax is follows:

PHP will execute condition condition, and if it evaluates to "true-ish" value (same semantics as an if() condition), value from expression-if-true is used. If condition evaluates to false, value from expression-if-false will be used.

An ideal use case of Ternary operator would be assignments that can have two values.

From PHP 8.0+, you can also throw an exception from a Ternary operator .

2. Shorthand Ternary Operator: cond ?: else-expr

Certain Ternary operator expressions can be simplified further. Consider the following Ternary expression:

If the conditional expression is the same as the true-expression, it is possible to reduce this further:

If load_user() function returns a false-ish value, $user will be assigned false . Otherwise, the return value of load_user() will be assigned.

Its syntax is:

The cond condition will be evaluated as if it's in an if() block, and the return value will be assigned to result if it is a truthy value. If it's a false-ish value (such as 0 , "0" , false , null , [] , etc), the expression-if-false expression will be evaluated, and its return value will be assigned to result .

3. Null Coalescing Operator

Null Coalescing Operator provides a shorthand for isset() calls. It is often used to reduce excessive isset() calls. Null Coalescing operator calls isset() on the conditional expression, and the value will be returned.

If $_GET['value'] is set (which behaves exactly the way isset() does), $_GET['value'] value will be assigned to $result . If it is not set, or null , foo will be assigned to $result .

PHP calls isset(variable) , and variable will be assigned to result if variable is set. If it is not set, expression will be evaluated, and its value will be assigned to result .

4. Null Coalescing Assignment operator

Null Coalescing operator can be be further reduced in PHP 7.4, with Null Coalescing Assignment operator .

A word of caution

Be mindful when you chain ternary/coalescing operators. It is now required to use braces to make the intent clear if you absolutely have to use ternary/coalescing operators.

Null Coalescing Assignment operator is relatively new in PHP (added in PHP 7.4), so you code might not work in older PHP versions if you decide to use that operator.

These operators are syntax sugar only, and do not provide any meaningful performance difference compared to good ol' if/else blocks. When the intent is not clear, it is recommended to go with if/else blocks although they make the code slightly verbose

Recent Articles on PHP.Watch

How to fix PHP Curl HTTPS Certificate Authority issues on Windows

How to fix PHP Curl HTTPS Certificate Authority issues on Windows

AEGIS Encryption with PHP Sodium Extension

AEGIS Encryption with PHP Sodium Extension

How to Install/Upgrade PHP 8.3 on MacOS with Homebrew

How to Install/Upgrade PHP 8.3 on MacOS with Homebrew

You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what's changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.

How To Do Almost Anything

How to Use the PHP Ternary Operator

November 11, 2007 by Doogie - Copyright - All Rights Reserved

The ternary operator is a shortcut comparison operator that replaces an if-else statement in a PHP script. If you use a lot of comparison statements in your scripts, this can greatly reduce the number of lines of code. The ternary operator is really very simple to use, but it does tend to confuse newbie PHP programmers.

The ternary operator is only used for assignment of values to variables and to reduce the lines of code and compact PHP statements. Although it is a little more difficult to read, once you understand how it operates, it is simple to use and understand.

There are four parts to a ternary statement. The first is the variable where the result of the conditional test will be assigned. The second part is he condition that is being evaluated for a True or False boolean result. The third part is the value that is assigned if the condition is true. The last part is the value assigned if the condition is false.

Let’s start with the most common use of this shortcut. If your scripts are processing large amounts of data that users have entered using HTML forms, you are undoubtedly assigning the form values to variables. When a value does not exist, a default value would normally be assigned like this:

Using a ternary operator statement, that same conditional test and assignment of values would look like this:

The interpretation is: If a value has been passed in the form variable named statusID via the POST method, assign that value to $statusID. If no value was passed, assign the default value of 1.

Sometimes you will see a variation of the same statement that looks like this:

The result will be the same, but the condition being tested has been flipped–rather than testing to see if a value does exist, it is testing to see if a value is missing. The interpretation is: If a no value has been passed via the POST method, assign the default value of 1. If a value was passed, assign that value to $statusID.

Ternary operators really shine when assigning text to simple messages, such as:

The interpretation is: If the value in $age is less than 21, then “Minor, no drinks” is assigned to $msg, else “Adult – have a beer” is assigned.

Here is a cool method for assigning alternating background colors to table rows or other tabular displays of data.

Running this code will display the following:

While this example uses an array, it is just as simple to do the same using data extracted from MySQL.

IMAGES

  1. PHP If Else Statement and Ternary Operator Tutorial

    php assign variable ternary

  2. PHP

    php assign variable ternary

  3. PHP Ternary Operators (Examples)

    php assign variable ternary

  4. Assign by Reference with Ternary Operator in PHP

    php assign variable ternary

  5. Cara Menggunakan Operator Ternary Di Php Dan Contoh Casenya Aneiqbal

    php assign variable ternary

  6. How To Use PHP Ternary Operator For If...else Condition Example

    php assign variable ternary

VIDEO

  1. 2

  2. Assign by Reference with Ternary Operator in PHP

  3. Assign users permission using PHP/MySQL

  4. Manage Tables in KNIME Rename, Sort, Filter, and Assign Variable Types

  5. PHP Assign Multiple Values

  6. PHP Assign String to a Variable

COMMENTS

  1. ternary operator

    Too bad PHP didn't go with the Javascript/Actionscript solution: Because a value processed in a conditional is not cast to boolean unless it's combined with && you can do var x = expensive() || default; This uses an already-familiar syntax and would benefit PHP in more than just one somewhat esoteric case. -

  2. PHP Ternary Operator

    Summary: in this tutorial, you will learn to use the PHP ternary operator to make the code shorter and more readable. Introduction to the PHP ternary operator The ternary operator is a shorthand for the if...else statement.

  3. PHP

    When we use ternary operator: We use the ternary operator when we need to simplify the if-else statements that are simply assigning values to variables depending on a condition. An advantage of using a ternary operator is that it reduces the huge if-else block to a single line, improving the code readability and simplify it.

  4. Understanding PHP Ternary Operator: A Comprehensive Guide

    PHP is one of the most commonly used scripting languages for web development. While working with PHP, you may come across situations where you want to assign a value to a variable based on a certain condition. This is where the PHP ternary operator comes into play. The ternary operator is a shorthand way of writing simple if-else statements.

  5. Crash Course in the PHP Ternary Operator With Examples

    In the above example, if the $_GET['limit'] variable is set, it would call another ternary expression, which checks if the value of the $_GET['limit'] variable is greater than 100. If so, it would return 10, otherwise it would return the actual value of the $_GET['limit'] variable. If the value of the $_GET['limit'] variable is not set, it would default to 10.

  6. PHP Ternary Operator: A Complete Guide

    This example effectively illustrates the utility of the compact ternary operator in PHP for streamlined code and efficient value assignment. Implementing Nested Ternary Operators in PHP In PHP, it's possible to nest ternary operators within each other by using parentheses for more complex conditional logic.

  7. PHP: Comparison

    Example #3 Assigning a default value <?php // Example usage for: Ternary Operator ... Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. ... It is recommended to avoid "stacking ...

  8. PHP Ternary Operator: Craft Clear Conditional

    The PHP Ternary Operator is a shorthand syntax for an if-else statement. It provides a concise way to write conditional expressions in a single line of code. The usage of the ternary operator is frequent when assigning values to variables based on specific conditions. Let's take a look at its syntax in PHP. The Basic Syntax

  9. Using the Ternary Operator in PHP

    The ternary operator in PHP is a conditional operator that allows you to execute a statement based on whether a condition is true or false. Using the ternary operator is just like writing an "if…else" statement in PHP, but more concise and potentially more readable. This PHP operator is best used when you need to assign a variable a value ...

  10. PHP Ternary Operator

    When to Use Ternary Operator. You can use the ternary operator when there is a need to simplify if-else statements or if the programmer wants to make efficient code out of a complex program structure. Moreover, conditional statements are also used while assigning post data or validate forms within an application. Advantages of Ternary Operator

  11. php

    The OR operator is shortcutting the second assignments you're making within the expressions of your ternary. So the second assignment isn't getting made if the first evaluates to non zero. If you switch to an AND statment (or &&) the second assignment in the expression is still dependant on the first: if the first evaluates to 0 (i.e. false), then the second half of the AND is not evaluated.

  12. PHP: Ternary Operator

    How to use the Ternary Operator in PHP. The syntax of a ternary IF statement in PHP looks like this: (Condition) ? (Do this if condition is TRUE) : (Do this if condition is FALSE) Take the following piece of code as an example: //Basic ternary.

  13. Mastering Ternary Operator in PHP

    Conclusion. The ternary operator in PHP is a powerful tool for writing concise and readable conditional statements. Throughout this tutorial, we've explored its use across various scenarios, illustrating how to effectively use it to streamline your PHP code. Remember that readability should always come first, so use ternary operators wisely.

  14. PHP: Assignment

    Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. ... 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.

  15. PHP

    PHP — P27: Ternary Operator. The ternary operator is a way to quickly express if/else statements. The ternary operator follows the following syntax: If the boolean expression evaluates to true, the "if_true" result is displayed, otherwise the "if_false" result is displayed. View this article and others on my website.

  16. Assigning variables by reference and ternary operator?

    Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference.

  17. How to use the PHP Ternary Operator

    The ternary operator is a conditional operator that decreases the length of code while performing comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this operator is from left to right. Obviously, it is the best case for a time-saving option.

  18. Ternary and Ternary Coalescing Operator in PHP • PHP.Watch

    PHP supports various forms of ternary and coalescing operators. This is a quick post to catch-up to all ternary and coalescing operators supports in PHP. 1. Ternary Operator: cond ? expr1 : expr2. Ternary operator is a short form for an if/else block that executes exactly one expression each.

  19. PHP Shortcuts

    The ternary operator is really very simple to use, but it does tend to confuse newbie PHP programmers. The ternary operator is only used for assignment of values to variables and to reduce the lines of code and compact PHP statements. Although it is a little more difficult to read, once you understand how it operates, it is simple to use and ...

  20. How to assign values to multiple variables using ternary operator in php?

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams Create a free Team

  21. php

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams Create a free Team