PHP: Check if variable exist but also if has a value equal to something

php isset
php empty
php isset vs empty
php check if variable exists
check if array has empty values php
php empty array
php check if session variable exists
php check if($_get parameter exists)

I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:

What I'm doing and think is not the best way to do:

if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something

My question is, exist any way to do this without declare the variable twice?

That is a simple case but imagine have to compare many of this $myvar variables.

Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:

$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));

The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.

Or you can use something like that:

$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $m ) {
    $_GET[$m] = null;
}

Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.

Update

One other way to clean up the code would be using a function that checks if the value is set.

function getValue($key) {
    if (!isset($_GET[$key])) {
        return false;
    }
    return $_GET[$key];
}

if (getValue('myvar') == 'something') {
    // Do something
}

isset - Manual, isset() will return FALSE when checking a variable that has been assigned to NULL . Also note that a null character ("\0") is not equivalent to the PHP NULL constant. Returns TRUE if var exists and has any value other than NULL . isset() only works with variables as passing anything else will result in a parse error. For  It will return true if the $variable is defined. if the variable is not defined it will return false. Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise. If you want to check for false, 0 etc You can then use empty () -. $isTouch = empty($variable); empty () works for -.

If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:

if ((isset($variable) ? $variable : null) == $value) { }

The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.

empty - Manual, A variable is considered empty if it does not exist or if its value equals FALSE Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse Returns FALSE if var exists and has a non-empty, non-zero value. See Also ¶ I confirm those results, and if you extend the test with isset($x->a->b->c) it  Suppose I have this table: id | name | city ----- 1 | n1 | c1 2 | n2 | c2 3 | n3 | c3 4 | n4 | c4 I want to check if the value c7 exists under the variable city or not. If it does, I will do something. If it doesn't, I will do something else.

As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:

$_GET['myvar'] = 'hello';
if (($_GET['myvar'] ?? '') == 'hello') {
    echo "hello!";
}

Output:

hello!

In general, the expression

$a ?? $b

is equivalent to

isset($a) ? $a : $b

How to use isset(), empty(), & is_null() in PHP, A variable is considered empty if it does not exist or if its value equals FALSE . empty() does If a variable has been unset with unset(), it will no longer be set. isset() will If you are using empty() you can test if a variable is false, but also if the variable does not exist. Usually that'll look something like this:. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

As mellowsoon suggest, you might consider this approach:

required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $key => $default  ) {
    $_GET[$key] = $default  ;
}

You put the default values and set the not recieved parameters to a default value :)

PHP empty() Function, Also check whether the variable is set/declared: <?php $a = 0; This function returns false if the variable exists and is not empty, otherwise it returns true. PHP has different functions which can be used to test the value of a variable. Three useful functions for this are isset (), empty () and is_null (). All these function return a boolean value. If these functions are not used in correct way they can cause unexpected results. isset () and empty () are often viewed as functions that are opposite, however this is not always true.

My question is, exist any way to do this without declare the variable twice?

No, there is no way to do this correctly without doing two checks. I hate it, too.

One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)

Why to check both isset() and !empty() function in PHP , The isset() function is an inbuilt function in PHP which checks whether a This function also checks if a declared variable, array or array key has null value, if it does, considerably equal to !isset() function and !empty() function is equal to isset() will not generate any warning or e-notice when the variable does not exists. Determine if a variable is considered set, this means if a variable is declared and is different than NULL . If a variable has been unset with the unset () function, it is no longer considered to be set. isset () will return FALSE when checking a variable that has been assigned to NULL .

The Definitive Guide To PHP's isset And empty, PHP has two very similar functions that are essential to writing good PHP But there's also the legitimate case of simply not knowing whether a Returns true if the variable does not exist or its value equals false in a In a nutshell, isset performs a $var !== null check in a way that does not trigger an error. Checks whether the given constant exists and is defined. Note: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

Determine if a variable is set and is not NULL, Also note that a null character ("\0") is not equivalent to the PHP NULL constant. Returns TRUE if var exists and has value other than NULL , FALSE otherwise. isset() only works with variables as passing anything else will result in a parse​  Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

PHP isset() vs empty() vs is_null(), Yes we use isset() to see if the variable exists and then use empty() to check if the variable has value or not. If we don't use isset() and directly use empty(), there  The is_numeric() function in the PHP programming language is used to evaluate whether a value is a number or numeric string. Numeric strings contain any number of digits, optional signs such as + or -, an optional decimal, and an optional exponential.

Comments
  • PHP doesn't have a solution for this, but it's a programming language. You can (and ought to) always write a subprogram to shorten a repetitive code. Not to mention that in a good program every variable should be defined before use...
  • Well I saw this around there, just hoping be possible without using arrays, thanks.
  • Updated my answer to show a possible way to do this without using another array.
  • Upvote the below answer that mentions ($var ?? 'value'). That's the most concise way to do it now thanks to PHP 7.
  • It is better to suggest === than ==, as it will not have the downside you mention.
  • If you use PHP7 it can be simpler if (($variable ?? null) === $value).
  • Just define all your variables. That's the point of all that mess.
  • Thank you Pekka, is really very boring do that.
  • Sometimes in a big system is difficult predict when the variable will appear, that why declare the variable may not help. But you're right in most of the cases.
  • @Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.