PHP Booleans

PHP Boolean is a data type, which helps to show two states, these are called true or false in programming. True is generally given a value of 1, and False is given a value of 0. You can set them just like other variables in PHP programming. It is used in control structure like the testing part of if statement. It is typically signified by “bool” or “boolean”.

Any non-zero values and non empty string are also measured as TRUE value. When you like to declare Boolean variables, you can declare as given below:

boolean $variable;

Where, Boolean denotes the type of the variable.

You can also state variable without data type, in such case PHP will strive to show the type of variable based on the value hold by that variable. For instance, if you assign a string value to a variable, this variable becomes a string variable. Below, see a variable without its type.

Here, $variable is a variable of type Boolean. We also demonstrate you the example of the validation page in which you can see that how Booleans work?

$variable= true;

How PHP Booleans work?

Step 1: PHP Code (form_validation.php) page.

<form action=”” method=“post” >

<div class=“main-form-div”>

<div class=“field-name”> Enter Value </div>

<div class=“field-value”>

<input name=“bool_val” type=“text”   id=“bool_val”>

</div>

<div class=“clearfix”></div>

<div>

<input type=“submit” name=“Submit” value=“Check Boolean”>

</div>

</div>

</form>

<title> PHP Booleans </title>

<?php

if(isset($_REQUEST[“Submit”]))

{

$qry=$_POST[bool_val];

// value true

if ($qry == true)

{

echo “Entered value is true”;

return true;

}

// value is false

if ($qry == false)

{

echo “Entered value is false”;

return false;

}

}

?>

Result:

PHP Booleans

PHP Booleans

Another example to have more clear understanding of this:

<div class="main-form-div">

<div class="field-name"> Enter value </div>

<div class="field-value">

<input name="bool_val" type="text"   id=" bool_val ">

</div>

<div class="clearfix"> </div>

<div>

<input type="submit" name="Submit"  value="check Boolean">

</div>

</div>

</form>

<title> PHP Booleans </title>

<?php

if(isset($_REQUEST["Submit"]))

{

$qry=$_POST[bool_val];

print (bool) $qry;

}

?>

Result:

php-booleans3

When we enter any value greater than or equal to 1 than it return true. For true, it returns one.




Leave a Reply

avatar
  Subscribe  
Notify of