Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - refactoring this if statement to avoid duplication

In this snippet of code we type $inputs['user_id'] 3 times.

if (isset($inputs['user_id']) && $inputs['user_id']) { // The consumer is passing a user_id
    doSomethingWith($inputs['user_id']);
}

What's the most readable and robust refactoring I can do to avoid the duplication and avoid any notice that the index user_id doesn't exist?

Thanks.

like image 575
Dan Avatar asked Sep 02 '26 14:09

Dan


1 Answers

Here nothing is wrong with the duplication. You cannot assign $inputs['user_id'] to a variable before checking if it is set, otherwise this will produce a Notice undefined index ....

The only thing here could be done is to omit the isset call and use !empty instead, like this:

if(!empty($inputs['user_id'])) {
    doSomething($inputs['user_id']);
}

Now You are only typing it twice and the check

!empty($inputs['user_id'])

equals to

isset($inputs['user_id']) && $inputs['user_id']

EDIT: based on a comments, here is a quote from documentation:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

So either empty(0) or empty('0') will return true, that means

if(!empty('0') || !empty(0)) { echo "SCREW YOU!"; }

will echo nothing... Or, in polite way, I will repeat the statement above:

!empty($inputs['user_id']) === (isset($inputs['user_id']) && $inputs['user_id'])

EDIT 2:

By omitting the isset and replacing by !empty the variable is still checked, whether the index is already set, please read the documentation, which says:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

like image 199
shadyyx Avatar answered Sep 05 '26 04:09

shadyyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!