0
<?php
function isset_n_empty($var) {
    if (isset($var) && !empty($var)){
        return true;
    }
    return false;
}
echo isset_n_empty($x ?? null);

?>

my function is supposed to do the simple if (isset() && !empty()) logic and i used $x ?? null because if it is not used it would give me this error for undefined variables as the example

E_NOTICE : type 8 -- Undefined variable: x -- at line z

is it redundant or well-optimized?

Mark Elvis
  • 51
  • 7

4 Answers4

0

A variable that isn't set is considered empty by empty().

Therefore, if the variable is not set, it is also empty.

Your code could be shortened by using:

echo !empty($x);

I suppose that makes the answer to your question yes.

Stratadox
  • 1,291
  • 8
  • 21
0

yes, the isset is redundant. if it's !empty(), then isset() always returns true.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
0

No the function is not redundant. It tells you if your variable is set but also falsey. There's nothing wrong with it.

On the other hand it seems like something that shouldn't really require a function of it's own. Instead of:

echo isset_n_empty($x ?? null);

You can just do:

echo isset($x) && !$x;

It's less code and doesn't require a function.

0

I hope this will help:

function isset_not_empty($var){
    if(!isset($var))
        return false;
    else
         return (!empty($var))

 }
Waelio
  • 59
  • 1
  • 9