I am reading a book and the author is using the following function. I don't understand the benefit of the equal operator. Can anybody please explain the reason for using the equal operator.
public function isDiscounted()
{
return 0 == $this->getRow()->discountPercent ? false : true;
}
Would it not be easier to go for
public function isDiscounted()
{
return $this->getRow()->discountPercent ? false : true;
}
?
Best regards,
Herbert
In your example you would need to swap the true and false:
return $this->getRow()->discountPercent ? true : false;
However you could just cast the integer return to a boolean:
return (bool)$this->getRow()->discountPercent;
Or even:
return 0 != $this->getRow()->discountPercent;
There's no need for the ternary returning true or false.
The benefit of the == operator is to make the program's intent clearer, that you're comparing a numeric variable with zero. It's equivalent to writing:
if (0 == $this->getRow()->discountPercent) {
return false;
} else {
return true;
}
You could also write it as:
return $this->getRow()->discountPercent ? true : false;
but this suggests that discountPercent is a boolean value, not numeric. Similarly, you could write:
return !$this->getRow()->discountPercent;
but this also suggests that it's boolean. While PHP is flexible with types like this, treating all non-falsy values as true, the original code is easier for human readers to understand.
In PHP you can do a loose comparison or a strict comparison. It really depends what you are trying to compare for, sometimes the loose is fine, sometimes you need it to be strict.
loose vs strict
/** loose **/
0 == 0; // true
0 == false; // true
0 == ''; // true
0 == null; // true
/** strict **/
0 === 0; // true
0 === false; // false
0 === ''; // false
0 === null; // false
as it pertains to your example
/**
* When doing the loose comparison, anything is isn't
* 0, false, '', or null will always evaluate to true.
*
* So for instance:
*/
'iamateapot' == true; // true
'false' == true; // true, this is true because it's a string of false not a boolean of false;
0 == true; // false;
In your particular case you are doing
$this->getRow()->discountPercent ? false : true;
Which is doing a loose comparison, my preference is to always specify what you are comparing against, so your first example would be what I would personally choose.
No, it's not easier to go for
return $this->getRow()->discountPercent ? false : true
In fact, it's wrong. You are supposed to return false if discountPercent is zero. In your suggested code, if discountPercent is zero, it will evaluate to false since it's used as a condition and return true.
If you truly want to keep the same logic but make it shorter the best way to go about it would be:
return $this->getRow()->discountPercent != 0
I have a rule I always follow: If the result of a conditional statement is a boolean, then return/condition itself. Also, I disagree that writing:
return 0 == $this->getRow()->discountPercent ? false : true;
makes the code more readable. If we go by what the function is supposed to do, I would write it something like this:
return $this->getRow()->discountPercent > 0
which clearly indicates that if discountPercent has a value greater than zero then it is discounted. Simple, precise and clear. It also takes care of negative values then.
Related
I have a boolean field that is represented by 0 and 1 in my database.
if ($request->input('submitted')) {
// do code
}
This has been working because it's only been setting the field to 1 (true) but now there's a new flow that can revert the submission.
It has not been setting it back to 0 when I pass the value 0 in from the frontend and I assume it's because that condition is getting skipped since 0 would eval to null.
Is the best way to handle it:
if (isset($request->input('submitted'))) {
// do code
}
or would strictly checking against null work better:
if ($request->input('submitted') !== null) {
// do code
}
The simply approach parse your input to a boolean.
if ((bool) $request->input('submitted')) {
This will create the following results. Therefor removing your edge case.
(bool) "1" // true
(bool) "1" // false
An alternative approach is to use inbuilt PHP filter, it will parse a lot of cases more notably "true" and "false" to true and false.
if (filter_var($request->input('submitted'), FILTER_VALIDATE_BOOLEAN)) {
I'm modelling an access function that should return boolean value based on next structure on nested array, which contains only boolean values:
based on dimension, comparison of the should be made either OR or AND type
first level is OR, next level is AND, next level is OR and so on
final result should return TRUE or FALSE
For example I have these arrays with expected results:
array(TRUE) -> TRUE
array(FALSE) -> FALSE
evidently...
array(TRUE, FALSE) -> TRUE
because of TRUE | FALSE
array(TRUE, array(FALSE)) -> TRUE
because of TRUE | (FALSE)
array(FALSE, array(FALSE, TRUE)) -> FALSE
because of FALSE | (FALSE && TRUE)
array(FALSE, array(TRUE, array(FALSE, TRUE))) -> TRUE
because of FALSE | (TRUE && (FALSE | TRUE))
What I'm doing here is just changing comparison method on every other level of the nested array.
PHP language example would be nice, but any prototype that I can transfer to PHP is accepted as an answer.
This is an example of mutual-recursion, using the array_reduce function
do_or applies the OR operator on the entire array
do_and applies the AND operator on the entire array
if an element of the array is an array itself, the functions apply each other
The Code:
function do_or($x,$y)
{
if (is_array($y))
{
if (empty($y))
{$y=FALSE;}
else
{$y=array_reduce($y,"do_and",TRUE);}
}
return $x||$y;
}
function do_and($x,$y)
{
if (is_array($y))
{
if (empty($y))
{$y=TRUE;}
else
{$y=array_reduce($y,"do_or",FALSE);}
}
return $x && $y;
}
$answer=array_reduce($arr,"do_or",FALSE);
This code could be optimized, but I guess it illustrates the idea
The documentation for filter_input() mentions :
Value of the requested variable on success, FALSE if the filter fails,
or NULL if the variable_name variable is not set.
After studying the various examples online, I was surprised to see that none of them (that I know of at least) checked for the value FALSE. Most of the examples only checked for the NULL value :
if ( is_null( filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING ) ) ) {
// display error
}
Is there a reason for this ? Or is there a real life example that does check for the FALSE value ? If so, would you kindly provide the example so that I may benefit from it.
Also, would you kindly provide the circumstances in which the filter_input could possibly fail. Much appreciated.
This is because !0 is true. Why? By adding the ! you are doing a boolean check, so your variable gets converted. And according to the manual:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
So the integer 0 gets converted to false while all other integers are converted to true.
This is why you need to do a type safe check for false or null as these are the values filter_input() returns if it fails for some reason
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
if ($name === false) {
//filter failed
}
if ($name === null) {
//variable was not set
}
In the PHP documentation for json_decode it says it can return TRUE,FALSE,NULL.
Could some help me understand when it would return FALSE? I understand invalid JSON will return NULL, but when would the other two be returned if not the actual JSON value?
Thanks
JSON format definition clearly shows all possible values and their representations:
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array.
Both objects and arrays have special syntax in JSON representation (wrapped in {} and [] respectively), so they can't be mixed up with false in any case. The same goes with string - it's wrapped in "" (double quotation marks). As for Numbers, they have to contain at least one digit - so cannot be confused with false (and true and null) too.
So that leaves us with the only case: when json_encode processes an object having redefined its JSON representation. For example (PHP 5.4+):
class FalsyFoo implements JsonSerializable {
public $foo;
public function __construct($f) {
$this->foo = $f;
}
public function jsonSerialize() {
return false;
}
}
$f = new FalsyFoo(true);
$fj = json_encode($f);
var_dump( $fj ); // string(5) 'false'
var_dump( json_decode($fj) ); // bool(false)
Technically, we still work with false value here, but the source is obviously different.
If you're still not convinced, check the source code of json_decode, which calls php_json_decode_ex after checking the arguments. This, in turn, calls parse_JSON_ex first, which operates over the predefined state transition table; the latter has only one set of states leading to false value as result. If this call fails somehow, value is checked directly:
if (str_len == 4) {
if (!strcasecmp(str, "null")) {
/* We need to explicitly clear the error
because its an actual NULL and not an error */
jp->error_code = PHP_JSON_ERROR_NONE;
RETVAL_NULL();
} else if (!strcasecmp(str, "true")) {
RETVAL_BOOL(1);
}
} else if (str_len == 5 && !strcasecmp(str, "false")) {
RETVAL_BOOL(0);
}
... and that's the only case when return_value is set to boolean.
The documentation says that values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. This means that if the booleans true orfalse are in the object to be encoded, they will be shows as TRUE or FALSE, and the same for null. For example:
json_decode('["hello",true]');
would return:
["hello",TRUE]
It doesn't mean that json_decode will return values of true, false, or null
I have this if statement
if (!(#$donnees['mode']['delete'] === true || #$donnees['mode']['display'] === true)){
//doSomething only if mode is not delete nor display
}
i used # to not get the notice when mode is not set.
because if i use isset instead it would be even uglier :
$cond_delete = isset($donnees['mode']['delete']) && $donnees['mode']['delete'] === true;
$cond_display = isset($donnees['mode']['display ']) && $donnees['mode']['display '] === true;
if (!($cond_delete || $cond_display)){
//doSomething only if mode is not delete nor display
}
Is there a more concise way to do this ?
Thanks
If $donnees[ 'mode' ][ 'delete' ] / $donnees[ 'mode' ][ 'display' ] will only ever be A) set to true, or else B) set to false or something that would be considered false when converting to boolean -- e.g. undefined, NULL, 0, "0", empty string -- then you can omit the === true and just let them evaluate to true or false. E.g.:
if ( ! (
#$donnees[ 'mode' ][ 'delete' ] ||
#$donnees[ 'mode' ][ 'display' ]
) ) {
// doSomething only if mode is not delete nor display
}
// if
What other elements may $donnees[ 'mode' ] contain?
Unless you're just learning to program and don't know what you're doing yet, then notices (E_NOTICE) are just a nuisance and I'd disable them if possible. With notices disabled, if you want to know if an array element actually exists, then you can use array_key_exists() or isset(), depending exactly what you're trying to find out. If you just want to access the variable / array element and have it evaluate to NULL if it's undefined (which will evaluate to false when converting to boolean, as in an if / else expression), then you don't need to bloat your code with unnecessary tests that add no value.
Something like this might be a good choice although it creates a couple of single use variables.
/*Either set values if setting available, or set false*/
$cond_delete = isset($donnees['mode']['delete'])? $donnees['mode']['delete']: false;
$cond_display = isset($donnees['mode']['display '])? $donnees['mode']['display ']: false;
/*Where either mode is set do something*/
if (!($cond_delete || $cond_display)){
//doSomething only if mode is not delete nor display
}
if (isset($donnees['mode']['delete'], $donnees['mode']['display']) AND ($donnees['mode']['delete'] === true || $donnees['mode']['display'] === true)){
//doSomething only if mode is not delete nor display
}