PHP operators (! $a vs. false === $a) - php

What is the difference, specifically in PHP? Logically they're the same (or so seem), but is there any advantage with one over the other? Including micro-benchmarking if any difference.
Example code:
$a = fc();
// Example 1
if (!$a) echo "Ex. 1";
// Example 2
if (false === $a) echo "Ex. 2";
// Example 3
if (true !== $a) echo "Ex. 3";
function fc()
{
return false;
}

!
Just invert your result value (boolean or not) from true to false or false to true
Example:
if (!file_exists('/path/file.jpg')) {
// if file NOT exists
}
=== false (or true)
The value compared MUST BE a boolean false or true.
Example:
$name = 'Patrick Maciel';
if ($name === true) {
// not is, because "Patrick Maciel" is a String
}
BUT if you do that
if ($name == true) {
// it is! Because $name is not null
// and the value is not 'false': $name = false;
}
In this case, this operator is just for check that:
$connection = $this->database_connection_up();
if ($connection === true) {
echo 'connected to database';
} else {
echo 'error in connection';
}
$valid_credit_card = $this->validate_credit_card($information);
if ($valid_credit_card === false) {
echo 'Your credit card information is invalid'
}
!== true (or false)
It's the same thing. Only the opposite of ===, ie: the value cannot be a boolean true or false.
Sorry for my english.

The difference boils down to type juggling. The ! operator converts a value to its boolean value, then inverts that value. === false simply checks if the value is, in fact, false. If it's not false, the comparison will be false.
If the value being compared is guaranteed to be a boolean, these operations will behave identically. If the value being compared could be a non-boolean, the operations are very much different. Compare:
php > $a="0";
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(false)
php > $a = false;
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(true)

Related

PHP if() does not return true nor calls all elements

I have following part of code:
if (($product->uploadable_files != $files_count || $product->text_fields != $text_count) && !count($this->errors) && !$product->update())
$this->errors[] = Tools::displayError('An error occurred while updating the custom configuration.');
How come (I'm completly lost atm) it does not call Tools::displayError nor $product->update()
At last one of those, should be called. And it is not.
This probably means it doesn't even reach that point. You can group the if-statement in three groups:
1st: $product->uploadable_files != $files_count || $product->text_fields != $text_count
2nd: !count($this->errors)
3rd: !$product->update()
If one of those groups is false, the entire condition will be false. And if 1st is false, it doesn't even reach 2nd and 3rd. And if 2nd is false, it doesn't reach 3rd.
Also, count never returns false. You're probably checking whether $this->errors is empty, so just use empty($this->errors).
To expand on treegarden's answer,
count() can evaluate to true if its handled incorrectly.
var_dump(count([])); # 0
var_dump(count([]) == false); # true
var_dump(count([]) === false); # false
Count returns the number of elements in in the first parameter. If the parameter is not an array or object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
Instead use empty():
var_dump(!empty([])); # false
&& checks if both are true. If first one is false, it ends there, doesnt go anywhere else, it is a short-circuit as manual says. Same goes for ||.
http://php.net/manual/en/language.operators.logical.php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
// --------------------
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
var_dump($e, $f);
// --------------------
// "&&" has a greater precedence than "and"
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
?>

How to check the value and type of a unknown var

I have a variable that can be int or bool, this is because the db from where im querying it change the variable type at some point from bool to int, where now 1 is true and 0 is false.
Since php is "delicate" with the '===' i like to ask if this is the correct why to know if that var is true:
if($wallet->locked === 1 || $wallet->locked === true)
I think in this way im asking for: is the type is int and one? or is the var type bool and true?
How will you approach this problem?
Your code is the correct way.
It indeed checks if the type is integer and the value is 1, or the type is boolean and the value is true.
The expression ($x === 1 || $x === true) will be false in every other case.
If you know your variable is an integer or boolean already, and you're okay with all integers other than 0 evaluating to true, then you can just use:
if($wallet->locked) {
Which will be true whenever the above expression is, but also for values like -1, 2, 1000 or any other non-zero integer.
$wallet->locked = 1;
if($wallet->locked === true){
echo 'true';
}else{
echo 'false';
}
will produce:
false
and
$wallet->locked = 1;
if($wallet->locked == true){
echo 'true';
}else{
echo 'false';
}
will produce:
true
Let me know if that helps!
Your solution seems to be perfect, but You can also use gettype. After that You can check the return value with "integer" or "boolean". Depending on the result You can process the data the way You need it.
solution #1. If $wallet has the value of either false or 0, then PHP will not bother to check its type (because && operator is short-circuit in PHP):
$wallet = true;
//$wallet = 1;
if( $wallet && (gettype($wallet) == "integer" || gettype($wallet) == "boolean") )
{ echo "This value is either 'true and 1' OR it is '1 and an integer'"; }
else { echo "This value is not true"; }
solution #2 (depending on what You want to achieve):
$wallet = 0;
//$wallet = 1; // $wallet = 25;
//$wallet = true;
//$wallet = false;
if($wallet)
{ echo "This value is true"; }
else { echo "This value is not true"; }

Working with PHP functions

I have this function that will check if a user already exists in the DB or not:
function checkTwitterAccount($user_id) {
$accountExists = false;
$a = "SELECT * FROM twitterAccounts WHERE user_id='".$user_id."'";
$ar=mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
if ($ac > 0) {
$accountExists = true;
}
return $accountExists;
}
Now when I call this function how do I actually know if the user is or is not in the DB?
I mean how do I call this function and how do I check the result?
Is the below right?
If (checkTwitterAccount($user_id) = true) {
DO THIS
}else{
DO THAT
}
Please help me I am new to it.
Thanks
if (checkTwitterAccount($user_id)) { //true
//do something
} else { //false
//do something
}
if (checkTwitterAccount($user_id) == true) {
//do this
}
else {
//do that
}
You have to use == rather than = as the = operand sets the value to true in the code you wrote, whereas the == operand compares the returned value to true.
Since your returning a true or false value you can simply use:
If (checkTwitterAccount($user_id)) {
//DO THIS
}else{
//DO THAT
}
Note: that your original line:
If (checkTwitterAccount($user_id) = true) {
would result in an assignment error because a single "=" means assign a value which can't be done to a function. You wanted:
If (checkTwitterAccount($user_id) == true) {
because "==" compares a value. Further, == only compares the value so for example 0 is the compares positively with false, any number compares positively with true, if you want to also compare type you us "===" like this:
0 == false //true
0 === false //false
false == false //true
false === false //true
1 == true //true
1 === true //false
true == true //true
true === true //true
function checkTwitterAccount($user_id) {
$user_id = intval($user_id);
$a = "SELECT `user_id` FROM `twitterAccounts` WHERE `user_id` = '".mysql_real_escape_string($user_id)."'";
$ar = mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
return ($ac > 0);
}
if(checkTwitterAccount($someid)) {
// Exists...
} else {
// No such ID in the DB
}
Note that comparison operator is == not = (which is assign).
So you could do:
if(checkTwitterAccount($someid) == true) {
However, it isn't necessary here.
Also remember to sanitize the data in the query.
if (checkTwitterAccount($user_id) == true){
do something if its true
} else {
do something if its flase
}
should work.. given that you provide argument to that function which seems to be
the int.. or id number from id column from users table in the db.
Basically you have a HTML Form that takes in a username and checks the database
for that users id number in users table in the database. Once it has this number it will
pass it on to the function checkTwitterAccount($user_id) if that function returns True that means guessing by the name of the function that the user has a twitter account else he does not have one.
you could do:
if (checkTwitterAccount($user_id) == true){
echo "This user has a twitter account";
} else {
echo "This user does not have a twitter account";
}
You can shorten the orig. function.
function checkTwitterAccount($user_id) {
$a = "SELECT * FROM twitterAccounts WHERE user_id='" . $user_id . "'";
$ar = mysql_query($a) or die("Error selecting twitter account: " . mysql_error());
return mysql_num_rows($ar) > 0; // boolean (will be true or false)
}
Then use the answer from max_. (See comparison operators)

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

Empty PHP variables

Is there a better way besides isset() or empty() to test for an empty variable?
It depends upon the context.
isset() will ONLY return true when the value of the variable is not NULL (and thereby the variable is at least defined).
empty() will return true when the value of the variable is deemed to be an "empty" value, typically this means 0, "0", NULL, FALSE, array() (an empty array) and "" (an empty string), anything else is not empty.
Some examples
FALSE == isset($foo);
TRUE == empty($foo);
$foo = NULL;
FALSE == isset($foo);
TRUE == empty($foo);
$foo = 0;
TRUE == isset($foo);
TRUE == empty($foo);
$foo = 1;
TRUE == isset($foo);
FALSE == empty($foo);
Keep an eye out for some of the strange == results you get with PHP though; you may need to use === to get the result you expect, e.g.
if (0 == '') {
echo "weird, huh?\n";
}
if (0 === '') {
echo "weird, huh?\n";
} else {
echo "that makes more sense\n";
}
Because 0 is false, and an empty string is false, 0 == '' is the same as FALSE == FALSE, which is true. Using === forces PHP to check types as well.

Categories