Issue where is_null not working even when conditions are false - php

In the code below when $start_limit and $end_limit are FALSE then A should be run. Instead B is occurring. I've tested that both variables are FALSE with var_dump.
I am using is_null because $start_limit is occasionally set to 0 and I want a condition where 0 counts as TRUE.
if (is_null($start_limit) && is_null($end_limit)) {
A
} else {
B
}
Any suggestions as to how to get A to run when both variables are FALSE would be very much appreciated .

Just use coercion-to-boolean. !0 and !false both evaluate to true.
if (!$start_limit && !$end_limit) {
// A
} else {
// B
}
http://ideone.com/aBbWJ

I think you want to use === instead of is_null. False is not null, but 0 !== false. The triple equality check is the type of exact matching you are looking for.
perhaps
if( false === $start_limit && !$end_limit ) {
// there are no limits, set the course for the heart of the sun!
}
else {
B
}

Related

What does while ($variable) mean in PHP?

I am new to PHP and am currently constructing a do/while loop from a tutorial. I would understand if the whole condition was ($variable == true) or ($variable == false), however in the tutorial the while condition is simply while($variable). Could anyone explain this to me?
Here is the tutorial code.
<?php
$loopCond = false;
do {
echo "<p>The loop ran even though the loop condition is false.</p>";
} while ($loopCond);
echo "<p>Now the loop is done running.</p>";
?>
All such conditional statements, including while and if, are evaluating the given expression against true. If the expression results in true, the statement executes the action. If it results in false, it won't.
$var == true is an expression which compares $var to true. The result of this expression is either true or false. The important point to understand here is expressions. Expressions are things which return values. Try var_dump($var == true) or var_dump(4 > 6). It shows you that the expressions return a boolean value. Here:
if ($var == true)
first $var is compared to true, which yields either the value true or false, which is then evaluated by if whether it's true or false, which then prompts if to execute the following statement or not.
In other words: it's redundant.
if ($var)
This simply causes if to evaluate whether $var is true or false and then execute the following statement. The == true is essentially already "built in".
The following statements are all essentially equivalent:
if ($var)
if ($var == true)
if (($var == true) == true)
if ((($var == true)) == true) == true)
...
A boolean value true or false should not be used with a redundant $c == true as the result is the same as $c: true or false
$driving = true;
while ($driving) {
while ($driving == true) { // ugly
while (! $driving) { // while not driving.
while ($driving == false) { // ugly
$drinking = ! $driving;
if ($driving && $drinking) {
Hence also use adjectives for boolean variables.
A condition is met, if the value or statement in it is considered as true.
The code $variable == true is a statement that looks whether the value of the variable is true and if it is, yields true - Or false if it is not.
However, as this means, that $variable itself can only ultimately be true or false, you don't even need the statement, as its return value will also be one of those two.
Therefore $variable is exactly the same as $variable == true.
I hope this made it clear.
The semantic of while/do-while is
while(<boolean expression>) {
// do your stuff
}
A boolean expression is anything that evaluates to true or false. So, if $loopCount is true, then $loopCount == true is checked on every loop and evalutes to true. But you could also write $LoopCount as condition, since it also evaluates to true.
This is very handy for using other data types, e.g. integers.
$count = 0;
while ($count < 10) {
$count = $count +1;
}
Here $count < 10 is a boolean expression that evaluates to true as long as $count is not higher then 9.
A while loop runs as long as the condition is met, in other words, as long as the boolean expression you provide evaluates to true.
You can also just use a variable, e.g. $loopCount when that variable evaluates to a boolean or a constant (even the constant value true).
Like Padarom said: Therefore $variable is exactly the same as $variable == true.
In your case: The while-do loop determines if redo the loop-body after the first run. Means the loop-body is executed exactly one time regardless what value $variable has. After the first run, the while($variable) checks if the expression is true. If so, the loop-body is executed second time and so forth.
Check PHP reference for do-while loops here. PHP.net do-while reference
while ($loopCond) and while ($loopCond == true) is the same thing. It checks the "trueness" of whatever you put in the brackets.
If I ask a question "does sun set in the west ? " what would be your answer, definitely YES OR TRUE. Same as compiler always look for statement value. Take a look
$condition = true;
if($condition == true )
// above will return TRUE; in short $condition == true will replaced by true at runtime. But if we place true directly which is $condition value or can say we place $condition instead true thus statement become shorten and look like...
if($condition) {
}

Return integer 0

Sorry for bad english , used Google.translate
There is a code that returns a value to a int, if set . Otherwise it returns false
if (isset($this->variable))
return intval ($this->variable);
else
return false;
On the receiving side condition
if ($return_value) {
// Here code
}
The problem is that if the returned value is 0, this is false, and the code is executed . But as the value of 0 is also important to me . If returned as a string , it is still treated as false.
define ('false', 'value') does not work.
Introduced his constant for this , but you have to rewrite a bunch of code for additional testing
(if($return_value! == my_false_constant)
That is not quite satisfied.
What options are there to solve this problem ?
if ($return_value !== false) {
}
Using !== (or ===) instead of just != or == also tests the type of the value.
Use strict comparison with ===.
See: http://us3.php.net/manual/en/types.comparisons.php
if(1 === true) //returns FALSE
This will work:
(if($return_value !== false){
// do work
}
Comparisons:
== means same value
=== means same value AND same type
! == means not (same value)
!== means not (same value and same type)
SO:
0 == false //is true
0 === false //is false
Simply ! == does not equal !==, as is not valid PHP code

Check if numeric and compare value in conditional with &&?

In PHP, if there is a conditional like this:
if ( is_numeric($my_var) && $my_var == 1 ) {
}
If the first part of the if is false, does the second part ($my_var == 1) get ever executed?
Thanks!
In your example the $my_var == 1 will not be executed (if it's not numeric). PHP will determinate that the first part evaluated to false and so there is no benefit in executing the second part because you are using the && AND operator.
An example:
if(isset($_GET['something']) && $_GET['something'] == '1')
{
}
If the querystring variable something is missing then it doesn't check if it equals 1. If it did then it could produce an Undefined index notice.
You can also verify this behavior with something like:
$test = '2';
if($test == '1' && die('dead'))
{
}
echo 'execution continues....';
Set $test = '2' and the die() will not stop execution. Set it to 1 and the die will execute and stop, thus you won't see Execution continues...
Edit: there is some general information here (not PHP specific).
If the first condition is false second one will not be executed if you use &&. You can try it yourself:
function a(){
echo 'a';
return true;
}
function b(){
echo 'b';
return true;
}
if (a() && b())
{
//do something
}
This will output: ab.
function a(){
echo 'a';
return false;
}
function b(){
echo 'b';
return true;
}
if (a() && b())
{
//do something
}
Outputs a.
I gave you this example because I couldn't find anything in docs but the first comment in this section
This is called a call-by-need or lazy evaluation.
Note: In some cases it's useful or necessary that the second function is executed despite of the state of first condition. In that cases you can use & operator. With bitwise operators you work with numbers, not with booleans. Because php interpretator should know both value before and after & operator it will execute both functions (a() & b()) and true, false are evaluated as 1 and 0, respectively, 1 & 0 => 0 that will be evaluated as false in if statement.
You can use like
if ( is_numeric($my_var)) {
if($my_var == 1)
{
// your code
}
}

Class Exists Check Comparison

Is there a diference between this comparisons ?
What is the diference between ! and === FALSE ?
if (!class_exists($class)) {
require($class.'.php');
}
if (class_exists($class) === FALSE) {
require($class.'.php');
}
In this case, no.
Some people think it's good programming style to explicitly show that they're comparing to a boolean. Personally... I don't like it, but I guess the more verbose form is more obvious, as the ! operator isnt the mose visible thing when smashed between a parenthesis and other vertically'ish characters.
Yes both are the different things:
php automatically considers 0 as "false" and 1 as "true" so when ever you use function response directly inside the if condition at that this both makes a difference.
consider a function, if executed properly at that it returns int number. it may be 0 too.
But if function did not match requirement at that it is returning false.
So at this time function returning value 0 is success. event though the result is zero. At this if you check this in if condition like
$return = someFunction();
if($return){
//code if ture
}
so if $return is 0 your if code will not be executed even your function execution was correct so in that case you should check like
$return = someFunction();
if($return !== FALSE){
//code if ture
}
=== and !== are used to check the response exactly match return type also.
if('0' === 0)
will return false
but
if('0' == 0)
will return true...
Hope your idea is clear now.
check this out:
if('0' == 0){
echo 'Hi, I will be in screen :)';
}
if('0' === 0){
echo 'I will not be in screen :(';
}

Test for query variable exists AND ALSO is set to a particular value?

I want to check if a query variable exists or not. Then I would do something based on that query value. If it exists and is true, do something. If it doesn't exist or is false, do something else such as show a 404 page.
e.g If the url was domain.com?konami=true
if (condition) {
//something
} else {
//show404
}
OPs question is a bit unclear. If you assume that he wants to check that konami is a $_GET parameter and that it has the value of "true" do:
if (isset($_GET["konami"]) === true && $_GET["konami"] === "true") {
// something
} else {
// show 404
}
The problem with the current accepted answer (by Cameron) is that it's lacking the isset check (which is unforgivable, it is objectively wrong). The problem of the highest voted answer (by Jan Hancic) is that it lacks the === "true" check (which is debatable, it depends on how your interpret the question).
Note that && is a lazy-and, meaning that if the first part is false, the second part will never be evaluated, which prevents the "Undefined index" warning. So the order of the statements is important.
Also note that $a === true is not the same as $a === "true". The first compares a boolean whereas the second compares a string.
If you do weak comparison $a == true you are checking for truthy-ness.
Many values are truthy, like the string "true", the number 1, and the string "foo".
Examples of falsy values are: empty string "", the number 0 and null.
"true" == true; // true
"foo" == true; // true
1 == true; // true
"" == true; // false
0 == true; // false
null == true; // false
"true" === true; // false
"true" === false; // false
There is a little confusion around what value should be tested. Do you want to test the konami parameter for being true in the sense of boolean, i.e. you want to test konami parameter for being truthy, or do you want to test if it has string value equal to "true"? Or do you want to test konami parameter for any value in general?
I guess what is wanted here is to test konami for a given string value, "true" in this case, and for being set at the same time. In this case, this is perfectly enough:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
...
if ($_GET['konami'] == "true")
...
This is enough, because if the $_GET['konami'] is unset, it cannot be equal to any string value except for "". Using === is not neccessary since you know that $_GET['konami'] is string.
Note that I turn off the E_NOTICE which someone may not like - but these type of "notices" are normally fine in many programming languages and you won't miss anything if you disable them. If you don't, you have to make your code unecessarily complex like this:
if (isset($_GET['konami']) && $_GET['konami'] == "true")
Do you really want to complicate your code with this, or rather make it simple and ignore the notices like Undefinex index? It's up to you.
Problems with other answers as you mentioned:
#Jan Hancic answer: it tests for true, not "true".
#Cameron answer: might be simplified and he didn't mention the necessity of disabling E_NOTICE.
#Frits van Campen's answer: too complex to my taste, unnecessary test for === true
Umm this?
if (isset($_GET['konami']) === true) {
// something
} else {
//show 404
}
Easy:
if(isset($_GET['konami']) && $_GET['konami'] != 'false') {
//something
} else {
// 404
}
quick and simple.
$konami = filter_input(INPUT_GET, 'konami', FILTER_VALIDATE_BOOLEAN) or die();
ref:
filter flags
filter_input
You may try this code. In this code checked two conditions by one if condition that is $konami contains value and $konami contains 'true'.
$konami = $_GET['konami'];
if( ($konami) && ($konami == "true")){
/*enter you true statement code */
}else {
/* enter your false statement code */
}
You can do it like this:
$konami = false;
if(isset($_GET['konami'])){
$konami = $_GET['konami'];
}
if($konami == "true"){
echo 'Hello World!';
}
else{
header('HTTP/1.0 404 Not Found');
}
In this case you'll always have $konami defined and - if set - filled with the value of your GET-parameter.
if(!$variable) {
//the variable is null
die("error, $variable is null");
}else{
//the variable is set, your code here.
$db->query("....");
}
This works best:
$konami = $_GET['konami'];
if($konami == "true")
{
echo 'Hello World!';
}
else
{
header('HTTP/1.0 404 Not Found');
}
Easiest and shortest way of doing it:
if($konami != null){ echo $konami; } else { header('HTTP/1.0 404 Not Found'); }

Categories