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

14

50

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.

Curvet answered 24/10, 2010 at 9:51 Comment(2)
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...Chau
In PHP 7+, many of these cases can be done by Null coalescing operator. Check this link out for use cases:Triacid
C
22

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
}
Carricarriage answered 24/10, 2010 at 10:5 Comment(3)
Well I saw this around there, just hoping be possible without using arrays, thanks.Curvet
Updated my answer to show a possible way to do this without using another array.Carricarriage
Upvote the below answer that mentions ($var ?? 'value'). That's the most concise way to do it now thanks to PHP 7.Withoutdoors
C
25

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

// $_GET['myvar'] isn't set...
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";

// $_GET['myvar'] is set but != 'hello'
$_GET['myvar'] = 'farewell';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";

// $_GET['myvar'] is set and == 'hello'
$_GET['myvar'] = 'hello';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";

Output:

goodbye!
goodbye!
hello!

Code demo on 3v4l.org

In general, the expression

$a ?? $b

is equivalent to

isset($a) ? $a : $b

Note that in the code example it is necessary to place parentheses around $_GET['myvar'] ?? '' as == has higher precedence than ?? and thus

$_GET['myvar'] ?? '' == 'hello'

would evaluate to:

$_GET['myvar'] ?? ('' == 'hello')

which would be true as long as $_GET['myvar'] was set and "truthy" (see the manual) and false otherwise (since '' == 'hello' is false).

Precedence code demo on 3v4l.org

Collywobbles answered 24/11, 2018 at 4:57 Comment(2)
What would happen if I omit the parenthesis?Wallache
@Wallache because of operator precedence (== is higher than ??), $_GET['myvar'] ?? '' == 'hello' would evaluate as $_GET['myvar'] ?? ('' == 'hello') so it would evaluate to true if either $_GET['myvar'] is unset (since 'hello' is "truthy") or if $_GET['myvar'] is a "truthy" value (see php.net/manual/en/language.types.boolean.php)Collywobbles
C
22

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
}
Carricarriage answered 24/10, 2010 at 10:5 Comment(3)
Well I saw this around there, just hoping be possible without using arrays, thanks.Curvet
Updated my answer to show a possible way to do this without using another array.Carricarriage
Upvote the below answer that mentions ($var ?? 'value'). That's the most concise way to do it now thanks to PHP 7.Withoutdoors
S
17

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.

Sitology answered 18/8, 2016 at 17:12 Comment(2)
It is better to suggest === than ==, as it will not have the downside you mention.Sontich
If you use PHP7 it can be simpler if (($variable ?? null) === $value).Declared
C
1

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.)

Chatty answered 24/10, 2010 at 10:2 Comment(5)
Just define all your variables. That's the point of all that mess.Chau
Thank you Pekka, is really very boring do that.Curvet
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.Curvet
@Mariz I disagree: It should never be difficult to predict when the variable will appear: If that is the case, you have bad code.Chatty
Pekka this is the "ideal", but that is difficult in a rush world with people from different background working in the same project. Anyway thanks people.Curvet
A
1

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 :)

Araucanian answered 5/10, 2011 at 13:36 Comment(0)
Z
1

A solution that I have found from playing around is to do:

if($x=&$_GET["myvar"] == "something")
{
    // do stuff with $x
}
Zoon answered 14/12, 2013 at 1:36 Comment(0)
S
1

This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.

$allowed = ["something","nothing"];
if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}

Here is a function for checking multiple values at once.

$arrKeys = array_keys($_GET);
$allowed = ["something","nothing"];

function checkGet($arrKeys,$allowed) { 
    foreach($arrKeys as $key ) {
        if(in_array($_GET[$key],$allowed)) {
            $values[$key];
        }
    }
    return $values;
}
Sacerdotalism answered 11/11, 2014 at 11:40 Comment(0)
Q
1

I am not a expert in PHP but I believe my solution may work since it worked for me and I will do this with a code I used just recently.

This is what I did and the logic.

  1. Using Isset I check to see if it had anything
  2. Used the forLoop to circle through the values
  3. As it circles check to see if the values equals to something I wanted!
  4. Tested it and yes it works
<?php
if (isset($_POST['growgroups'])) {
    echo '<h3>You have select the following grow groups</h3>';
    foreach ($_POST['growgroups'] as $growgroups) {
        echo '<p>' . $growgroups . '</p>';
        if ($growgroups === 'Fervent Foodies') {
            echo '<p>Great Choice!</p>';
        } 
        if ($growgroups === 'The Conversation') {
            echo '<p>Enjoy the converation!</p>';
        } 
    }
}
Quickly answered 28/3, 2023 at 13:49 Comment(0)
C
0

Thanks Mellowsoon and Pekka, I did some research here and come up with this:

  • Check and declare each variable as null (if is the case) before start to use (as recommended):
!isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;

*ok this one is simple but works fine, you can start to use the variable everywhere after this line

  • Using array to cover all cases:
$myvars = array( 'var1', 'var2', 'var3');
foreach($myvars as $key)
    !isset($_GET[$key]) ? $_GET[$key] =0:0;

*after that you are free to use your variables (var1, var2, var3 ... etc),

PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);

... Better approaches are welcome :)


UPDATE:

Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.

!isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;
Curvet answered 24/10, 2010 at 21:24 Comment(0)
P
0

why not create a function for doing this, convert the variable your want to check into a real variable, ex.

function _FX($name) { 
  if (isset($$name)) return $$name;
  else return null; 
}

then you do _FX('param') == '123', just a thought

Poach answered 24/8, 2011 at 1:29 Comment(1)
this will still fire an error notice when you call _FX('param')Rabbit
D
0

I use all time own useful function exst() which automatically declare variables.

Example -

$element1 = exst($arr["key1"]);
$val2 = exst($_POST["key2"], 'novalue');


/** 
 * Function exst() - Checks if the variable has been set 
 * (copy/paste it in any place of your code)
 * 
 * If the variable is set and not empty returns the variable (no transformation)
 * If the variable is not set or empty, returns the $default value
 *
 * @param  mixed $var
 * @param  mixed $default
 * 
 * @return mixed 
 */

function exst( & $var, $default = "")
{
    $t = "";
    if ( !isset($var)  || !$var ) {
        if (isset($default) && $default != "") $t = $default;
    }
    else  {  
        $t = $var;
    }
    if (is_string($t)) $t = trim($t);
    return $t;
}
Depart answered 10/4, 2013 at 12:1 Comment(1)
Unfortunately this triggers a PHP notice if the array key doesn't exist, does it not?Knickerbockers
R
0
<?php

function myset(&$var,$value=false){
    if(isset($var)):
        return $var == $value ? $value : false;
    endif;
    return false;
}

$array['key'] = 'foo';

var_dump(myset($array['key'],'bar')); //bool(false)

var_dump(myset($array['key'],'foo'));//string(3) "foo"

var_dump(myset($array['baz'],'bar'));//bool(false) 
Regulation answered 14/3, 2014 at 14:24 Comment(0)
R
-1

Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.

I think it's ok to do this inside conditional statements like above. No harm done really.

Reaction answered 24/10, 2010 at 12:28 Comment(3)
And it fires a notice, if the myvar index doesn't exist.Volition
True, but you're just testing for that index. IMHO it would only be really bad, if that if-clause didn't exist at all. A notice i can live with. After all, it's just a notice, which by definition are harmless (usually).Reaction
Oof, I couldn't disagree more. If your goal is to create a sloppy PHP codebase full of sneaky/silent bugs, ignoring notices would be a great way to start. You should always develop with notices turned on, and you should always treat them as bugs to be fixed.Uncomfortable
V
-3

No official reference but it worked when I tried this:

if (isset($_GET['myvar']) == 'something')
Vociferous answered 4/3, 2014 at 21:40 Comment(2)
Nope. This is comparing TRUE/FALSE against 'something'.Zuckerman
this will always be false, code inside if-block will never run.Echikson

© 2022 - 2024 — McMap. All rights reserved.