Is there a better way to do this if condition - php

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
}

Related

PHP multiple url's check and do action

Can't figure out how to check multiple URL's and stop loading selected plugin. With other plugins it's all good when need to check only one page, but when it comes to multiple pages - ain't working at all.
Code:
<?php
$request_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$is_admin = strpos( $request_uri, '/wp-admin/' );
if( false === $is_admin ){
add_filter( 'option_active_plugins', function( $plugins ){
global $request_uri;
$berocket_filter_plugin = "woocommerce-ajax-filters/woocommerce-filters.php";
$c = array_search( $berocket_filter_plugin, $plugins );
if( false !== $c && in_array( strpos ($request_uri, ['/shop/','/product-category/'], true ) )){
unset( $plugins[$c] );
}
return $plugins;
} );
}
I'm trying to check is page url is exactly 'shop' page slug, or contains '/product-category/' slug, as soon as I'm trying to use this array, it's not doing his work at all.
Any suggestions are appreciated!
To be honest I'm not a wordpress expert (I hate the bloody thing) but...
The strpos function second argument needs to be a string, you're passing in an array that evaluates to 0 I believe. And the 3rd argument is an offset on the sting, since you set it to true i believe that would evaluate to 1. So... what happens is:
in_array(strpos('myurl',0,1))
strpos('myurl',0,1) = 0 // as we're looking for a '0' in 'yurl'
consider working with the url as a dictionary. Instead of keeping it as a string run a no_empty explode to get something like:
['shop' => true,
'product-category' => true]
That way instead of running an array_search or strpos for each check you can simply invoke something along the lines of:
if(!isset($request_uri['wp-admin']) {...
if (
isset($request_uri['product-category']) ||
(count($request_uri) === 1 && isset($request_uri['shop']))
) {...}
}
There is a neater way to write this but this should be simple to read and understand the logic.
Similar approach goes for the plugins array. The only difference between [$id => $value] and [$value => $id] is the fact that you need to run a search on the array and check if it's set instead of simply checking if it's set.

If with false and 1 value in php

I have this code:
if($coupon->excluding_discounted){
if(!$product->price_after_discount){
// do something
}
}
The code worked perfectly but I thought to convert this to one if ...
dd($coupon->excluding_discounted,!$product->price_after_discount);
1
false
How to check if the value of something is 1 and another element is false to do something ...?
Update:
my full code:
$products->map(function($product) use($coupon){
if($coupon->excluding_discounted && !$product->price_after_discount){
user()->cart()->updateExistingPivot($product, [
'coupon_id' => $coupon->id,
]);
}
});
the logic of code is if the product has discount and the excluding_discounted in coupon is true do the reset of code
I tried like this but it store the coupon_id even there is a discount on product! but with if inside if worked perfectly
You can join if statements together, like so:
if ($coupon->excluding_discounted && !$product->price_after_discount) {
// do something
}
If you want to test strictly the value of a variable you can use the === operator :
if (1 === $coupon->excluding_discounted
&& false === $product->price_after_discount
) {
// do something here
}

Laravel: Passing a value of 0 back to controller from frontend

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)) {

PHP If Shorthand Best Practce

Just a weird PHP question about best practice.
Assuming the following function:
function get_option($val) {
return false;
}
I want to assign to a $locale variable, the value returned from this function and, if false, set to a default en_GB one.
I discovered 2 option for achieving this goal:
1st Option:
$locale = ( $locale = get_option( 'language_code' ) ) ? $locale : 'en_GB';
2nd Option:
$locale = get_option( 'language_code' ) ? get_option( 'language_code' ) : 'en_GB';
I would like to know which one is more correct and why.
Thanks
The second option is better, but even better would be to use a shorthand ternary
$locale = get_option('language_code') ?: 'en_GB';
If your function returns only locale strings or false, this is the correct solution (and it doesn't require PHP7).
However, as mentioned in the comments, it might be an idea to return default values directly from the get_option function for a more architecturally sound solution. That means the caller is not made responsible for setting the default.
Just read that you're using Wordpress and have no control over the inner workings of the function, but the advice in general still stands
Both seem a bit verbose to me, to avoid duplicated calculations, I would prefer the first one (perhaps splitted to 2 lines of code).
You can create a helper function, this one has false hardcoded, but you could even pass it as a parameter:
function use_default_false($var, $default) {
return ($var !== false) ? $var : $default;
}
Then your code becomes:
$locale = use_default_false(get_option('language_code'), 'GB');
Since PHP5.3 you can use the shorthand ternary operator ?:.
Be aware that it will check the left-hand side argument for truthy, which prevents it to be used if the valid value you're checking evaluates to false (e.g.: 0, "", "0", array()...). Because of that, I wouldn't generally recommend it, but in this case I assume the locale is a non-empty non-"0" string, so it should be fine.
$locale = get_option('language_code') ?: 'GB';
With PHP7 you can use the null coalesce operator ??.
It checks for NULL so you have to alter the default value returned by your function.
$locale = get_option('language_code') ?? 'GB';
I would prefer the second one
basically if get_option( 'language_code' ) returns true then get_option( 'language_code' ) execute else other option.
it is easier to understand, and maintainable.
for duplicate code issue use something similer to this:
you need to post some more code, but here is a better way to do it:
var var1 = null;
function get_option( somevar ){
if (var1 != null) {
return true;
} else {
var1 = do some stuff;
return true;
}
}
and then call the function like this
$locale = get_option( 'language_code' ) ? var1 : 'en_GB';

Comparison operator return 0 ==

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.

Categories