The best way to check the conditions - php

The best way to check the conditions and what is difference between them?
This is my usual way:
if ($this->_is_valid_number() == TRUE) {
//do some thing...
}
I've seen some code written in this way(for example):
if (TRUE == $this->_is_valid_number()) {
//do some thing...
}
Are these different from each other? Which method is standard?

None of the above, really.
== true is redundant with if(condition) so it could just be written as if ($this->_is_valid_number()) which is pretty standard. If you want to check for false, you would do if (!$this->_is_valid_number()) and if you would check for any other condition, you usually write like you would speak:
If my number is not one -> if($number !== 1)
Notice: Also check this article for difference between == and === operators

The second method has a added benefit of failing if it's used incorrect.
The second one sets true to $number and creates no error, which is what the code should do but not what the coder is expecting.
Do it the other way around and it will fail
$number =5;
if($number == true) echo "true"; // true
if($number = true) echo "true"; //true
if(true == $number) echo "true"; // true
if(true = $number) echo "true"; // fails
https://3v4l.org/suF9s

Related

PHP IF Statement - Two Variables Not Working

I have an IF statement and I need to check two variables, then execute the action if either of the variables are false.
I know I can use the OR (||) statement however for some reason it is not working. I am in the process of learning PHP so it's probably a syntax error on my behalf.
If I create the if statement with only one (either) variable, it works fine:
<?php if ($var1 == false) { do whatever...} ?>
However when I try to check two, neither of the variables seem to be checked. I have tried different syntax variations but nothing works:
<?php if (($var1 == false) || ($var2 == false)) { do whatever...} ?>
<?php if (($var1 == false) OR ($var2 == false)) { do whatever...} ?>
<?php if ($var1 == false || $var2 == false) { do whatever...} ?>
<?php if ($var1 == false OR $var2 == false) { do whatever...} ?>
Can someone please point out what my error is?
Thanks!
EDIT: Including the actual code.
<?php $member = $members_template->member; $bpmember = bp_get_member_user_id(); ?>
<?php $membersearchinclude = xprofile_get_field_data( 'Exclude yourself from website search results?', $bpmember ); ?>
<?php $adminsearchinclude = xprofile_get_field_data( 'Exclude From Search Results', $bpmember ); ?>
<?php if (($adminsearchinclude == false) || ($membersearchinclude == false)) { ?>
This is extracting the xprofile field state from two different checkboxes in BuddyPress. I am checking if either of the checkboxes are false, then executing code.
I have managed to solve the issue.
It seems my logical operators needed changing:
if ((!$adminsearchexclude) && (!$membersearchexclude))
I am sure if I posted the entire code one of you would have got it. This is a sensitive project at the moment at unfortunately posting the entire code wasn't an option.
Many thanks to everyone that chipped in especially #ChrisO'Kelly for the var dump snippets. You got me thinking in the right direction and I now have a new tool in my arsenal :)
THANK YOU ALL!!
I'm not sure what causing it to not run as expected because from my view its all valid. Try to post your code so we know the whole logic.
Try to use strict comparison.
$var1 = 0;
$var2 = 1;
// The echo will not be executed
if ($var1 === false || $var2 === false) {
echo "Strict comparison\n";
}
// The echo will be executed
if ($var1 == false || $var2 == false) {
echo "No strict comparison\n";
}
References:
http://php.net/manual/en/language.operators.logical.php
http://php.net/manual/en/language.operators.comparison.php

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';
}

PHP MySQL comparison always true regardless of operands and operator

For the record, I read documentation on boolean comparisons in PHP, but I do not understand how my code relates in this context. I thought I had a problem connecting to MySQL, but it turns out everything is fine and I can make queries without issue. So, MySQL is not really that relevant to this post.
I use this to report errors in an object that tried to connect on construction. Note that I tried ==, ===, != and !== only to get the same problem. I even tried casting the argument to bool and boolean.
Comments in below code blocks are relevant.
private function assert($test){ // Tried renaming in case PHP was funny about it.
if ($test === FALSE){ // Tried ==, ===, !== and != and casting $test.
if ($this->use_exception){
throw new mysql_exception();
}else{
die("MySQL ".mysql_errno()." - ".mysql_error());
}
}
}
Connecting is typical.
$this->con = mysql_connect($host, $un, $pw, false, $ssl ? MYSQL_CLIENT_SSL : 0);
// I get 'yay'
echo mysql_ping($this->con) ? "yay" : "nay";
// This disagrees. Tried no cast, and a cast to bool.
$this->assert((boolean)($this->con != FALSE));
mysql_ping() says everything is ok, but assert() stops the presses no matter what.
I tried every operator and cast combination, even renaming the function out of paranoia over a name clash. Why does assert() only see true?
EDIT:
To make my problem clearer, consider the alternative implementation with Eugen's suggested use of is_resource. The problem is that I just have no idea why the below happens.
private function assert($test){
$test = $test ? true : false;
if ($test === FALSE){
echo "$test === false<br />";
}
if ($test == FALSE){
echo "$test == false<br />";
}
if ($test !== FALSE){
echo "$test !== false<br />";
}
if ($test == FALSE){
echo "$test != false<br />";
}
}
Output is out of order and the value changed after one comparison. Since I can make queries, $test must be true. I should not get output at all, but I do for every operator. I also tried it with FALSE replaced by 0.
Bad PHP instance?
1 !== false
=== false
!== false
!= false
$this->assert(is_resource($this->con));
can't you use your second example and combine the function? you already get a value (yay/nay)
$this->con = mysql_connect($host, $un, $pw, false, $ssl ? MYSQL_CLIENT_SSL : 0);
$this->assert = mysql_ping($this->con) ? 1 : 0;
just thinking out loud

Catching hell with if's in php?

ok forgive my technique in writing here, but i can't seem to understand why this code recognizes things and then doesn't recognize some other things.
my code:
if (!isset($id)) {
$_SESSION["logged_in"] = False;
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
if ($_SESSION["logged_in"] = False)
{ echo "session variable is set at False"; }
if ( $_SESSION["logged_in"] = True)
{ echo "session variable is set at True"; }
}
now as I see it, if it enters this bit of code at all, the first thing that happens should be that the variable gets set to "false". elsewhere in some code not shown it gets set to true and that part works fine but when i try to force it into this for a false setting it remains true.. can anyone see why this wouldn't get set to "False" at this point in the execution?
You should be using == for comparison here, not = for assignment:
if ($_SESSION["logged_in"] = False)
// ---------------^^^
// Should be
if ($_SESSION["logged_in"] == False)
// Also here:
if ( $_SESSION["logged_in"] = True)
//--------------------------^^
// Should be
if ($_SESSION["logged_in"] == True)
You are making a classic mistake by assigning the variable in your if statement instead of comparing it. So, change your if statements to:
if ($_SESSION["logged_in"] == false)
Instead of (where you are assigning):
if ($_SESSION["logged_in"] = false)
By the way, you're statement has now some duplication since the variable itself already is true of false. So, there is no need to check it against the boolean. So, this can be enough:
if ($_SESSION["logged_in"]) //equals true if user is logged in
if (!$_SESSION["logged_in"]) // equals true if user is NOT logged in
You need == or ===
Using = means its equal :)
if (!isset($id)) {
$_SESSION["logged_in"] = False;
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
if ($_SESSION["logged_in"] == False)
{ echo "session variable is set at False"; }
if ( $_SESSION["logged_in"] == True)
{ echo "session variable is set at True"; }
}
You should be using the == operator rather than = in your if statements.
EG
if ($_SESSION["logged_in"] == False)

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