Booleans

Author Topic: Booleans  (Read 520 times)

Offline beingchinmayTopic starter

  • Trade Count: (0)
  • Jr. Member
  • **
  • Thank You 1
  • Posts: 73
  • Karma: 0
  • Gender: Male
  • I am Chinmay
    • Fat Cutter
Booleans
« on: 07-30-2016, 06:00:50 »
Booleans were introduced for the first time in PHP 4 and didn’t exist in prior versions. A Boolean value can be either true or false.


As previously mentioned, PHP automatically converts types when needed. Boolean is probably the type that other types are most often converted
to behind the scenes. This is because, in any conditional code such as if statements, loops, and so on, types are converted to this scalar type to check if the condition is satisfied. Also, comparison operators result in a Boolean value.

Consider the following code fragment:


Quote
$numerator = 1;
$denominator = 5;
if ($denominator == 0) {
print "The denominator needs to be a non-zero number\n";
}

The result of the equal-than operator is a Boolean; in this case, it would be false and, therefore, the if() statement would not be entered. Now, consider the next code fragment:

Quote
$numerator = 1;
$denominator = 5;
if ($denominator) {
/* Perform calculation */
} else {
print "The denominator needs to be a non-zero number\n";
}

You can see that no comparison operator was used in this example; however, PHP automatically internally converted $denominator or, to be more accurate, the value 5 to its Boolean equivalent, true, to perform the if() statement and, therefore, enter the calculation