If else condition is used to execute the block of code based on condition. If the given condition is not true then alternative code of block will be executed.
Syntax:
if (condition) {
// code to be executed if the given condition is true...
} else {
// code to be executed if the given condition is false...
}
You can see the above condition takes 4 lines of code. So when you have only simple one line statement to be executed in if... else
condition, then you use ternary operator.
Ternary operator(shorthand property) is same regular if...else condition in one line.
Syntax:
(condition) ? (statement to be executed for true condition) : (statement to be executed for false condition)
Example:
<?php
$x = 5;
$text = ($x < 10) ? 'variable is x is less than 10' : $text = 'variable x is greater than 10';
echo($text);
Or something like this:
<?php
$pass = true;
$result = ($pass) ? 'Passed' : 'Failed';
This is useful when assiging value to variable in form submit.
$first_name = isset($_POST['first_name']) ? $_POST['first_name'] : null;
The ternary operator reduces code be written and makes it more readable. Note that variable in conditional code should be already defined. Else it will give the error. I hope you like this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Node.js MySQL Update data Database Table
In this tutorial article, we will learn...Apache redirect http to https URL
After installing ssl certificate in your...PHP Parse and Process XML data
Sometimes working with 3rd party API, yo...How to set the width of a div element dynamically using jQuery
Use the JavaScript width() method You...How to Files Upload with Progress Bar Help of jQuery Ajax & PHP
The file upload feature is the most used...