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]
How to check if an element exists in jQuery
Use the jQuery .length Property You c...How to split a string into an array in PHP
Use the PHP explode() function...Laravel 8 queue and job example tutorial
In the previous article, we have discuss...How to Set CSS background-image Property Using jQuery
Use the jQuery CSS() Method To set th...Laravel 8 Load More Data on Page Scroll using Jquery Ajax
You have already known about Twitter and...