panthro panthro - 1 year ago 79
PHP Question

Check if two vars are set?

Depending on whether 2 vars are set ($skip and $take) I want to do different things. I have a large if else statement, is there a more efficient way to write this?

if (isset($skip) && !isset($take)) {
//skip only
} elseif (!isset($skip) && isset($take)) {
//take only
} elseif (isset($skip) && isset($take)) {
//skip and take
} else {


It should also be noted that this is to sit in a method where the vars will be set to null if not specified:

getAll($skip = null, $take = null)

Answer Source

Since the OP clarified in a comment that this is inside a method, and both $skip and $take are arguments with default values, one might favor === over isset. Furthermore, you can re-arrange the logic a bit:

function getAll($skip = null, $take = null) {

    if ($skip !== null && $take !== null) {
        // both
    } elseif ($skip !== null) {
        // skip only
    } elseif ($take !== null) {
        // take only
    } else {
        // none

The === operator enforces an equality check with type safety.

The way default values for arguments work, the arguments are always guaranteed to be null if you don't pass them, so the equality check is a good way to check them here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download