PHP: if(!$one == $two) doesn't work always? - php

Yes, this is just a question i would like to get an answer on. I experienced it a couple of times, where this:
if(!$one == $two){ echo "Not the same"; }else{ echo "The same"; }
Will not work, and
if($one == $two){ echo "The same"; }else{ echo "Not the same"; }
will work.
Why doesn't it work sometimes? I always need to recode like the second, when the first doesn't work.

! is having higher precedence than == so you should use parenthesis as:
if(!($one == $two))

You need to write
if(!($one == $two))
or
if($one != $two)
since the ! operator has a higher precedence than the == operator.
See also: http://www.php.net/manual/en/language.operators.precedence.php

You need
if(!($one == $two))
This is because without the brackets, it is checking if $one is false and then checking if $two == $one. The following is the only time that it will work without the brackets. Evaluating to if (true == true) as !$one = true.
$one = false;
$two = true;
if (!$one == $two)
{
echo "different";
}

Related

I am not understanding why this is happening with empty php variables

I try to do this:
if ($var !== ""){
$message = "whatever";
}
But end up having to do this:
if ($var == ""){
//do nothing
} else {
$message = "whatever";
}
Why does that happen? Shouldn't both of those mean the same thing?
!= and == are opposites (non-strict comparison operators).
!== and === are opposites (strict comparison operators, where the value must match what you are comparing exactly).
If you use != instead of !==, your code should work. But:
You should understand what the actual value of your variable is - it's not an empty string. You can use print_r( $var ); to see it.
It's better to use the strict comparison operators === and !==, because they have well-defined behavior that is easier to remember and debug.
As $var is really string just use:
if ($var){//any non-empty string will work fine as it will be casted to boolean automatically
$message = "whatever";
}
$var could be != '' but not= '' eg .. null
if ($var == ""){
//do nothing
} else {
if (is_null($var) {
$message ='NULL';
} else {
$message = "whatever";
}
}

PHP - Check GET Variables Exist And Not Empty

I want to check the GET variables are not empty, I tried ways but they didn't work.
So I had the code like this:
$u = isset($_GET["u"]);
$p = isset($_GET["p"]);
if ($u !== "" && $p !== "") {
//something
} else {
//do something
}
The I checked the code by sending create.php?u=&p=, but the code didn't work. It kept running the //do something part. The I tried:
echo $u;
echo $p;
It returned 1 and 1. Then I changed it to:
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "") {
//something
} else {
//do something
}
But it continued to run //do something.
Please help.
You can just use empty which is a PHP function. It will automatically check if it exists and whether there is any data in it:
if(empty($var))
{
// This variable is either not set or has nothing in it.
}
In your case, as you want to check AGAINST it being empty you can use:
if (!empty($u) && !empty($p))
{
// You can continue...
}
Edit: Additionally the comparison !== will check for not equal to AND of the same type. While in this case GET/POST data are strings, so the use is correct (comparing to an empty string), be careful when using this. The normal PHP comparison for not equal to is !=.
Additional Edit: Actually, (amusingly) it is. Had you used a != to do the comparison, it would have worked. As the == and != operators perform a loose comparison, false == "" returns true - hence your if statement code of ($u != "" && $p != "") would have worked the way you expected.
<?php
$var1=false;
$var2="";
$var3=0;
echo ($var1!=$var2)? "Not Equal" : "Equal";
echo ($var1!==$var2)? "Not Equal" : "Equal";
echo ($var1!=$var3)? "Not Equal" : "Equal";
echo ($var1!==$var3)? "Not Equal" : "Equal";
print_r($var1);
print_r($var2);
?>
// Output: Equal
// Output: Not Equal
// Output: Equal
// Output: Not Equal
Final edit: Change your condition in your if statement to:
if ($u != "" && $p != "")
It will work as you expected, it won't be the best way of doing it (nor the shortest) but it will work the way you intended.
Really the Final Edit:
Consider the following:
$u = isset($_GET["u"]); // Assuming GET is set, $u == TRUE
$p = isset($_GET["p"]); // Assuming GET is not set, $p == FALSE
Strict Comparisons:
if ($u !== "")
// (TRUE !== "" - is not met. Strict Comparison used - As expected)
if ($p !== "")
// (FALSE !== "" - is not met. Strict Comparison used - Not as expected)
While the Loose Comparisons:
if ($u != "")
// (TRUE != "" - is not met. Loose Comparison used - As expected)
if ($p != "")
// (FALSE != "" - is met. Loose Comparison used)
You need !empty()
if (!empty($_GET["p"]) && !empty($_GET["u"])) {
//something
} else {
//do something
}
Helpful Link
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "")
why are you using "!==" and not "!=".
to always simplify your problem solve the logic on paper once using the runtime $u and $p value.
To check if $_GET value is blank or not you can use 2 methods.
since $_GET is an array you can use if(count($_GET)) if you have only u and p to check or check all incoming $_GET parameters.
empty function #Fluffeh referred to.
if($_GET['u']!=""&&$_GET['p']!="")
Hope it helps thx
In you code you should correctly check the variable existence like
if ($u != NULL && $p != NULL && $u != 0 && $p != 0) {
//something
} else {
//do something
}
Wow! I was so dumb... isset returns a boolean. I fixed my problem now. Thank you for answering anyway :)
This fixes:
$u = $_GET["u"];
$p = $_GET["p"];

Some Confusion in IF Condition of PHP

This is the code
$a = 'Rs 15.25';
if ( $a != '' && $a! = 0 ) {
echo "Inside If";
} else {
echo "Outside If";
}
actually I want to Print "Inside If" so that's why I put $a='Some String Value'. But it always prints "Outside If". Then I changed my code to
$a = 'Rs 15.25';
if ( $a != '' && $a != '0' ) {
echo "Inside If";
} else {
echo "Outside If";
}
I have just added single quotes to 0. Then i got the exact output as i want. But I didn't understand why this happens.
So please help me with this.
PHP does weak type comparison, that is, it converts both operands to the same type before doing the actual comparison.
If one of the operands is a number, the other one is converted to a number as well. If the second operand is a string and contains no digits, it is silently converted to the number 0.
To avoid this whole issue, use string type checking with the operator !== (=== for equality).
if($a !== '' && $a !== 0) {
echo "Inside If";
} else {
echo "Outside If";
}
First of all you when you have multiple conditions on an if statement you should always enclose each of them within brackets
So first thing you should do is to change your code to
$a='Rs 15.25';
if(($a!='') && ($a!='0'))
{
echo "Inside If";
}else
{
echo "Outside If";
}
In PHP 0 = FALSE, 1 = TRUE.
if($a != 0) -> if($a != FALSE)
if $a = 'Rs 15.25', $a != false and $a not empty, then you have echo "Outside If";

Compare strings in PHP

I'm trying to compare a POST variable with a string. Can someone help me see what in my PHP code is not written correctly? I've tried both '==' and '==='. Thank you for your help.
$action = mysqli_real_escape_string($mysqli, $_POST['action']);
if(strcmp($action, "save") == 0){
//do stuff
}elseif(strcmp($action, "load") == 0){
//do other stuff
}else{
//do even more stuff
}
why not simply use
if ($_POST['action']=='save'){
}elseif($_POST['action']=='load'){
}
don't understand the mysql in this contenxt
Don't know why you want to do this, but try casting $aciton, like (string)$action.
== is used to see if the two sides of comparison are equal, while === is used to check to see if they're identical meaning they are equal AND of the same type.
As for your code, you should just be able to do
if($action == 'save'){
echo 'save';
}
elseif ($action == 'load'){
echo 'load';
}
else{
echo 'none';
}

Checking if isset and is true?

Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))

Categories