php why does TRUE == "expired"? - php

This drove me nuts for a few hours.
I have a function returning one of the three following values:
function checkValid() {
...
return array("expired",$oldDate,$newDate) ;
return array(true,$oldDate,$newDate) ;
return array(false,$oldDate,$newDate) ;
}
list($isValid,$oDate,$nDate) = checkValid() ;
if ($isValid == "expired") {
...
...do blah
}
...and everytime the condition returned true, the if ($isValid == "expired") { ... } would trigger. So I ran some tests and sure enough:
$isValid = true ;
if ($isValid == "expired") {
echo "Yup...some how 'expired' equals TRUE" ;
} else {
echo "Nope....it doesn't equal true" ;
}
output: Yup...some how 'expired' equals TRUE
When I changed the if/condition to:
$isValid = true ;
if ($isValid === "expired") {
echo "Yup...some how 'expired' equals TRUE" ;
} else {
echo "Nope....it doesn't equal true" ;
}
output: Nope....it doesn't equal true
I am baffled by this. Why would true == 'expired' or 1 == 'expired' ???

When using two equal signs == php does type coersion under the hood and checks for truthy cases which includes all numbers other than 0, boolean true, all string other than empty strings and some other cases.
If you want to check for an exact match, you should use three equal signs ===

Related

How to treat zero values as true using php?

Here is my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled:
1. true when I pass any value having 0.
2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?
The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
please notice I used !== not !=. this is why:
0 == "" // true
0 === "" // false
See more at http://php.net/manual/en/language.operators.comparison.php
also if you are expecting number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
since is_numeric("") returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively if you expect number good option is filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0
http://php.net/manual/en/function.filter-var.php
if(isset($_POST['issue_id'])) {
if($_POST['issue_id'] == 0) {
echo "true";
}
else {
echo "false";
}
}
When you get data from a form, remember:
All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.
This means that $_POST['issue_id'] will be the string '0', which is actually truthy.
If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);
#Abdus Sattar Bhuiyan you can also full fill your two condition like below one:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}

How does work if / else?

I have $first and $second. They can have value 0 or 1.
if ( $first AND $second ) {
// True
} else {
// False
}
My mind (and Google search) tells me, that the result is true only when $first == 1 and $second == 0 or vice versa. But the result is true when both of this variables are 1.
I don't understand how does it works.
Your Google searches have failed you. PHP's type juggling means that a 1 is equivalent to TRUE and 0 is equivalent to FALSE. (See also type comparisons). So if both values are 1 then that if statement evaluates to TRUE. If one or both values are 0, it evaluates to FALSE.
<?php
$one = 1;
$zero = 0;
if ($one && $one) {
echo "true\n";
}
else {
echo "false\n";
}
if ($zero && $zero) {
echo "true\n";
}
else {
echo "false\n";
}
if ($one && $zero) {
echo "true\n";
}
else {
echo "false\n";
}
if ($zero && $one) {
echo "true\n";
}
else {
echo "false\n";
}
Program Output
true
false
false
false
Demo
In PHP all values are either "truthy" or "falsy" in expressions.
If a value contains something then it can be said to be truthy. So, values such as 1, "one", [1,2,3] or true all "contain" something and will be interpreted as truthy.
Values that are zeroed or in some way empty are falsy. E.g. 0, "", [] and false.
There is a table of how values are interpreted in the PHP documentation.
You can also just experiment, and output it to your website:
var_dump(1 and 0);

PHP While loop with rand() and if statement for rand

this is my first post.
I am sorry for the totally amateur question but I want to learn PHP so I started doing some online courses-tutorials for PHP and there was an example without explanation and I can't find the answer on google.
In the code line 4 $flip = rand(0,1); that means that $flip is getting a random number 0 or 1 right?
Then at line 6 there is if ($flip) { ...
But they don't explain what "if ($flip)" means or equals to.
For example $flip = 1 or $flip = 0. Thank you in advance.
$headCount = 0;
$flipCount = 0;
while ($headCount < 3) {
$flip = rand(0,1);
$flipCount ++;
if ($flip){
$headCount ++;
echo "<div class=\"coin\">H</div>";
}
else {
$headCount = 0;
echo "<div class=\"coin\">T</div>";
}
}
echo "<p>It took {$flipCount} flips!</p>";
Basically In PHP expression is evaluated to its Boolean value. for e.g
if($flip) // means if(1) or if(0)
if (expr)
statement
0 : is evaluated as Boolean FALSE
if($flip){
}
else {
// goes here
}
1 : is evaluated as Boolean TRUE (non-zero)
if($flip){
// goes here
}
else {
}
If the value of the first expression is TRUE (non-zero) it enters into if block
You are correct in you first assumption:
$flip = rand(0,1);
$flip will be equal to either 0 or 1. The below for example:
$flip = rand(0,5);
Will return a number between 0 and 5 randomly.
Generally if you do an if statement like so
if($example)
You are testing if the value is true or false. True can also be expressed as 1 and false can also be expressed as 0.
Therefore as $flip is equal to a 0 or 1, it is equal to either true or false. So if flip is true or 1, then it will execute the code in the if statement. As a note you could reverse how the if works by testing for false using:
if(!$flip)
Effectively if $flip is greater than 0 it will be considered true, see the example below:
$test = 0;
if($test) //This will be false and therefore echo It is false
{
echo "It is true";
}
else
{
echo "It is false";
}
$test2 = 5;
if($test2) //This will be true and therefore echo It is true
{
echo "It is true";
}
else
{
echo "It is false";
}
Update
You could consider the following to effectively be the same:
if($flip)
if($flip == 1 || $flip == true || $flip > 0)
A variable equal to 0 means false, other numbers mean true :
if(0) => false // you go in the else statement
if(1) => true
if(2) => true
etc...
In fact, when you do if($flip), the test executed by PHP is if($flip != 0)

Please explain this php expression "!$variable"

What does an exclamaton mark in front of a variable mean? And how is it being used in this piece of code?
EDIT: From the answers so far I suspect that I also should mention that this code is in a function where one of the parameters is $mytype ....would this be a way of checking if $mytype was passed? - Thanks to all of the responders so far.
$myclass = null;
if ($mytype == null && ($PAGE->pagetype <> 'site-index' && $PAGE->pagetype <>'admin-index')) {
return $myclass;
}
elseif ($mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
$myclass = ' active_tree_node';
return $myclass;
}
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}`
The exclamation mark in PHP means not:
if($var)
means if $var is not null or zero or false while
if(!$var)
means if $var IS null or zero or false.
Think of it as a query along the lines of:
select someColumn where id = 3
and
select someColumn where id != 3
! negates the value of whatever it's put in front of. So the code you've posted checks to see if the negated value of $mytype is == to null.
return true; //true
return !true; //false
return false; //false
return !false; //true
return (4 > 10); //false
return !(4 < 10); //true
return true == false; //false
return !true == false; //true
return true XOR true; //false
return !true XOR true; //true
return !true XOR true; //false
! before variable negates it's value
this statement is actually same as !$mytype since FALSE == NULL
!$mytype == null
statement will return TRUE if $mytype contains one of these:
TRUE
number other than zero
non-empty string
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}
The above !$mytype == null is so wrong. !$mytype means that if the variable evaluates to false or is null, then the condition will execute.
However the extra == null is unnecessary and is basically saying if (false == null) or if (null == null)
!$variable used with If condition to check variable is Null or Not
For example
if(!$var)
means if $var IS null.

PHP compare doubt

if(0 == ('Pictures'))
{
echo 'true';
}
why it's giving me 'true' ?
Your string will be evaluated as an Integer, so becomes 0, use this : 0 === 'Pictures' that verifies identity (same value and same type)
Check PHP type comparison tables to understand how comparison operators behave in PHP.
In your case, 'Pictures' becomes "0" and therefore 0 = 0.
Let's check following example:
echo (int)'Pictures'; // 0 => 'Picture' as int
echo 0 == 'Pictures'; // 1 => true, 0 = 0
Use:
if (0 === 'Pictures')
{
echo 'true';
}
The === is strict type operator, it not only checks the value but the type as well.
Quick Test:
if(0 == 'Pictures')
{
echo 'true';
}
else
{
echo 'false';
}
outputs true but:
if(0 === 'Pictures')
{
echo 'true';
}
else
{
echo 'false';
}
outputs false

Categories