Logic Operators

  • Understanding Logical Operators

Logical Operators are operators used to compare 2 logical conditions, namely logically true (TRUE) and logically false (FALSE). Logical operators are often used for IF conditions, or for exiting the loop.

The operand type in this logical operator is a variable of type boolean. However, if the operand is not a boolean, it will be “converted” to a boolean by PHP (we discussed this “conversion” rule in the tutorial on PHP’s boolean data type).

  • Types of Logical Operators in PHP

Source: https://www.duniailkom.com/wp-content/uploads/2014/02/Tabel-Jenis-Operator-Logika-PHP.png

The difference between AND operators with &&, and OR with || related to the way of writing and the rules of “strength” operators. Operators && and || has a higher “power” than AND and OR, so the command line: $a AND $b || $c, will be executed by PHP as $a AND ($b || $c).

From the table above, I only give the result for the TRUE condition, then other than the condition, the result is FALSE.

  • Understanding the Short Circuit Principle in PHP Logic Operations

PHP performs logical operations with the short-circuit principle, that is, if by checking only one command, the logical result is found, then the other commands will not be executed. For example:

$hasil = $a AND $b AND $c AND $d;

If at the time the program is run $a is already FALSE, then the variables $b, $c and $d will not be checked again, because whatever the value of these variables, the result will still be FALSE.

This will be useful in certain cases, such as the following example:

1. <?php

2. $result = fopen($filename) or exit();

3. ?>

The exit() function in the PHP code (which will stop the PHP program from processing) will not run as long as fopen($filename) is true. This short-circuit function is often used in examples of PHP applications.

The need for digital IT is needed in daily activities, Bead IT Consultant is the right choice as your partner, visit our website by clicking this link: www.beadgroup.com