2

checking if all are set

if(
    isset($var1) &&
    isset($var2) &&
    isset($var3)
){}

can be re-written as

if(isset($var1,$var2,$var3)){}

but what's the syntax for if any are set?

if(
    isset($var1) ||
    isset($var2) ||
    isset($var3)
){}

Looks ugly; is there any better way to write this?

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167

2 Answers2

2

You have to pass strings instead of the variables, but for fun:

if(compact('var1', 'var2', 'var3')) {
    echo 'one or more is set';
} else {
    echo 'none are set';
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

I guess one could write a simple function to use, but there's probably a cleaner way.

function anyset(...$vars){
    foreach($vars as $var){
        if(isset($var)){
            return true;
        }
    }
    return false;
}

if(anyset($var1,$var2,$var3)){}
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
  • 1
    Just a sidenote: If you're not dealing with checkboxes and/or radios but actual inputs, it's best to use `empty()`. rather than `isset()` This Q&A http://stackoverflow.com/questions/8236354/php-is-null-or-empty may help shed some light on this, most particularly this answer in there http://stackoverflow.com/a/15607549/1415724 (after seeing your edit with nulls). – Funk Forty Niner Nov 08 '16 at 21:19
  • However, if `isset()` is the requirement, then using the same syntax for `empty()` as you did for `if(isset($var1,$var2,$var3))` won't work unfortunately. Would have been nice though and would have made it a lot easier. – Funk Forty Niner Nov 08 '16 at 21:21
  • @Fred-ii- hey! thanks for the note, and [I remember](http://stackoverflow.com/posts/comments/62693758) :) – Jeff Puckett Nov 08 '16 at 21:34
  • You're welcome Jeff. Wow... you've a better memory than me *lol!* Cheers – Funk Forty Niner Nov 08 '16 at 21:35
  • Well, I didn't exactly remember, but it rang a bell, so [I could dig for it](http://data.stackexchange.com/stackoverflow/query/574692). – Jeff Puckett Nov 08 '16 at 21:37
  • 1
    Ouuuuhhhh, db comments! Nice :-)) I don't believe I knew about that; now I do ;-) – Funk Forty Niner Nov 08 '16 at 21:38