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
}
}
Related
I'm not quite sure how to ask this but, I have the following PHP function:
<?php
function checkAge($age) {
return ($age >= 21);
}
?>
Which can be used on this conditional:
<?php
if(checkAge(21)) {
echo 'welcome to the club';
}
else {
echo 'sorry! you are younger than 21';
}
?>
When defining the function, I'm only saying return ($age >= 21) and it seems to be returning 'true'. Does that mean that using return like that will return a boolean?
I'm sorry if I'm not being clear, this really confused me :(
Thank you in advance!
return returns whatever you give to it. If what you give to it is an expression, the expression will be evaluated and its result will be returned. Here, you are returning an expression that evaluates to a boolean, so yes your function will return either true or false.
So your function checkAge is the same as:
// Just to explain. Don't do this!
function checkAge($age) {
if ($age >= 21) {
return true;
} else {
return false;
}
}
But:
Does PHP's 'return' statement return a boolean by default?
No.
What you pass to it is what will be returned. If nothing was passed to it, null will be returned.
return stops the execution of the current module and gives control back to the calling code. See - https://www.php.net/manual/en/function.return.php.
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call.
The boolean that you're getting is from your comparison expression $age >= 21. Comparison expressions always return a boolean. See - https://www.php.net/manual/en/language.expressions.php#language.expressions
As an example, these 2 pieces of code are functionally identical. They both compare 2 values and return a boolean.
<?php
if ($age >= 21) {
...
}
if (checkAge(21)) {
...
}
I'm trying to simplify some code. I've found that if you assign a value within an if statement, but the value ends up being null, then the evaluated if is FALSE.
Example:
if($myvar = doSomething()) {
echo '$myvar = '.$myvar;
}
else {
echo "was null";
}
function doSomething() {
$a = null;
return $a;
}
The script above will display "was null". However, if $a = 1, then it will display "myvar = 1".
I've tried to find some documentation around this behaviour but haven't been successful. All of my sources are close, but don't describe it well.
My question: Is this expected behaviour? If doSomething() returns null, is what I'm doing equivalent to if(null) {...?
EDIT: YES I mean '=' not '==' in the if statement. What I'm asking is it expected that this should always return false: if($a = null) whereas this returns true if($a = 1)
What you're doing is fully expected. The value of the assignment expression $a=b is the assigned value b. So,
if($myvar = doSomething()) { ...
is equivalent to
$myvar = doSomething();
if ($myvar) { ...
This behavior is completely unrelated to the if statement. The documentation clearly states, in the second paragraph:
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.
Try to call function in variable.
$getvar = doSomething();
if($myvar == $getvar) {
// stuff
}
I have noticed that PHP doesn't run the second or other parameters of 'if statement' if the first parameter true.
if($this->sessions->remove("registered_id") or $this->sessions->remove("user_id")){
echo "you have logged out";
}else {
echo "wth?";
}
This how I use the if. Also here is the remove function from sessions class.
public function remove($key){
if(isset($_SESSION[$key])){
unset($_SESSION[$key]);
return true;
}
else
{
return false;
}
}
The thing that I want to do is run both of this parameters.. I hope I can tell the problem..
You need to execute both functions, store their respective results, then test on these results.
$resultA = $this->sessions->remove("registered_id");
$resultB = $this->sessions->remove("user_id");
if ($resultA or $resultB)
{
…
It's by design that the second statement is not executed, because its result will be irrelevant.
If by other parameters you mean the second condition, then use an AND instead of OR
If by other parameters you mean the else, then use a separate if statement instead.
edit
If you're trying to execute both statements, use bitwise operators, check out this manual:
http://www.php.net/manual/en/language.operators.bitwise.php
Something like:
if(a | b){
}
That will execute both a and b, but still is an 'or' comparison.
That result is to be expected. This is what logical operators do.
You would need to use && or and to achieve what you seem to be looking for:
if ($this->sessions->remove("registered_id") && $this->sessions->remove("user_id")) {
Here is why:
The && or and keyword means that all evaluations must return true. So:
if ($a && $b) {
// $a and $b must both be true
// if $a is false, the value of $b is not even checked
}
The || or or keyword means that either evaluation must return true. So:
if ($a || $b) {
// Either $a or $b must be true
// If $a is false, the parser continues to see if $b might still be true
// If $a is true, $b is not evaluated, as our check is already satisfied
}
So in your case, if the $this->sessions->remove("registered_id") successfully did it's thing, the $this->sessions->remove("user_id") is never called, as our check is already satisfied with the outcome of the first call.
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 :(';
}
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'); }