PHP Operators: Ternary Operator



PHP Operators Step By Step Tutorial - Part 7: Ternary operator is the other condition of operator which evaluates the expression of representing moderation model of if... else.... statement. Ternary operator is written down with ?:. Its syntax:
(expr1) ? (expr2) : (expr3);

If expr1 is evaluated as true, hence expr2 is done, while if expr2 is evaluated as false, hence expr3 is done.

Pay attention to the example of using Ternary operator at script as following:

File name: ternaryoperator.php

<html>
<head>
<title>Using Ternary Operator</title>
</head>

<body>
<h1>Using Ternary operator</h1>
<?
	$x = 15;
	$y = 7;
	$z = ($x > $y)?($x / $y):($y * $x);
	printf ("x = %d <br>", $x);
	printf ("y = %d <br>", $y);
	printf ("z = %d <br>", $z);
	$value = 95;
	$info = ($value>=60)? "Pass": "Do not pass";
	printf ("value = %d <br>",$value);
	printf ("info = %s", $info);
?>
</body>
</html>

The result of executing ternaryoperator.php:

ternary operator


Series this article:
PHP Operators: Introduction
PHP Operators: Arithmetic Operators
PHP Operators: Assignment Operators
PHP Operators: Assignment Operators Table
PHP Operators: Bitwise Operators
PHP Operators: Relation Operators
PHP Operators: Ternary Operator
PHP Operators: Error Control Operator
PHP Operators: Execution Operator
PHP Operators: Increment or Decrement Operator
php Operators: Logic Operator
PHP Operators: String Operator
PHP Operators: Array Operator
PHP Operators: Object Operator
PHP Operators: Operator Priority
PHP Constants: Introduction


Tag: operator, Ternary Operator Category: PHP Basic Post : March 08th 2008 Read: 1,807 Bookmark and Share

blog comments powered by Disqus