Advertisement:
Read Later
Did you know that you can write shorter and most importantly more coherent in connecting logical statements, using conditional assignment operators - Ternary and Null coalescing - instead of if and else operators in PHP? In this tutorial, I will show you how to create a function returning test values depending on either pre-defined logical conditions or whether entered variables exist.
PHP Operators(*)
Aside from conditional assigment operators shown in this tutorial, there are other types of PHP operators listed below:
Create a function named as triangle.
Define three variables to be evaluated - var_1, var_2, var_3.
In this particular function, I used conditional assignment operators - Ternary and Null coalescing - to detect triangles depending on sides as test values.
Using ?:(Ternary) operator, return "check" null if any given variable is a string.
Using ??(Null coalescing) operator, if "check" is null, proceed detecting triangles; else print the pre-defined "check" value(Enter Integers!).
Detect if it is possible to draw a triangle with given variables in "result" using the pow() function and ?:(Ternary) operator.
If a triangle is detected, print "Triangle Detected :)"; else print "Not A Triangle!".
<--------PHP---------->
<?php
function triangle($var_1, $var_2, $var_3){
$check = (is_string($var_1) || is_string($var_2) || is_string($var_3)) ? "Enter Integers!" : null;
$result = (pow((int)$var_1, 2) == pow((int)$var_2, 2) + pow((int)$var_3, 2)) ? "Triangle Detected :)" : "Not A Triangle!";
echo $check ?? $result;
}
?>
Result:
(5, 4, 3) = Triangle Detected :)
(1, 2, 3) = Not A Triangle!
("hello", "world", 8) = Enter Integers!
(*) https://www.w3schools.com/php/php_operators.asp