PHP:检查变量是否存在,但也检查其值是否等于某个值

发布于 2024-09-28 12:09:50 字数 310 浏览 9 评论 0原文

我有(或没有)一个来自查询字符串的变量 $_GET['myvar'] ,我想检查该变量是否存在,以及该值是否对应于我的 if 语句中的某些内容:

什么我正在做并且认为这不是最好的方法:

if(isset($_GET['myvar']) && $_GET['myvar'] == 'something') :做某事

我的问题是,是否有任何方法可以在不声明变量两次的情况下执行此操作?

这是一个简单的情况,但想象一下必须比较许多 $myvar 变量。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

孤独患者 2024-10-05 12:09:50

从 PHP7 开始,您可以使用 空合并运算符 ?? 以避免双重引用:

// $_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

一般来说,表达式

$a ?? $b

是等价的请

isset($a) ? $a : $b

注意,在代码示例中,需要在 $_GET['myvar'] 周围放置括号? '' 因为 == 的优先级高于 ??,因此

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

计算结果为:

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

只要 $_GET['myvar '] 已设置且“真实”(请参阅​​手册< /a>),否则为 false(因为 '' == 'hello' 为 false)。

优先级代码3v4l.org 上的演示

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

情深已缘浅 2024-10-05 12:09:50

遗憾的是,这是唯一的方法。但是有一些方法可以处理更大的数组。例如:

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

变量 $missing 现在包含所需值的列表,但在 $_GET 数组中缺失。您可以使用 $missing 数组向访问者显示消息。

或者你可以使用类似的东西:

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

现在每个必需的元素至少有一个默认值。您现在可以使用 if($_GET['myvar'] == 'something') ,而不必担心未设置密钥。

更新

另一种清理代码的方法是使用检查值是否已设置的函数。

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

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

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
}
趁年轻赶紧闹 2024-10-05 12:09:50

如果您正在寻找一个单行代码来检查您不确定是否已设置的变量的值,那么这是可行的:

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

唯一可能的缺点是,如果您正在测试 true/ false - null 将被解释为等于 false

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.

荒岛晴空 2024-10-05 12:09:50

我的问题是,有没有办法在不声明变量两次的情况下做到这一点?

不,如果不进行两次检查,就无法正确执行此操作。 我也讨厌它。

解决这个问题的一种方法是导入所有相关的 GET 变量在一个中心点放入数组或某种类型的对象中(大多数 MVC 框架会自动执行此操作),并设置稍后需要的所有属性。 (而不是通过代码访问请求变量。)

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

思念绕指尖 2024-10-05 12:09:50

正如 mellowsoon 所建议的,您可能会考虑这种方法:

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  ;
}

您输入默认值并将未收到的参数设置为默认值:)

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

相对绾红妆 2024-10-05 12:09:50

我从玩弄中发现的一个解决方案是:

if($x=&$_GET["myvar"] == "something")
{
    // do stuff with $x
}

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

if($x=&$_GET["myvar"] == "something")
{
    // do stuff with $x
}
百合的盛世恋 2024-10-05 12:09:50

我不是 PHP 专家,但我相信我的解决方案可能有效,因为它对我有用,我将使用我最近使用的代码来完成此操作。

这就是我所做的和逻辑。

  1. 使用 Isset 我检查它是否有任何内容
  2. 使用 forLoop 循环遍历值
  3. 当它循环检查值是否等于我想要的值时!
  4. 测试了一下,是的,它有效
<?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>';
        } 
    }
}

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>';
        } 
    }
}
话少情深 2024-10-05 12:09:50

感谢 Mellowsoon 和 Pekka,我在这里做了一些研究并提出了这个:

  • 在开始使用之前检查并声明每个变量为 null(如果是这种情况)(按照推荐):
!isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;

*好的,这个很简单,但工作正常,您可以在此行之后开始在任何地方使用变量

  • 使用数组覆盖所有情况:
$myvars = array( 'var1', 'var2', 'var3');
foreach($myvars as $key)
    !isset($_GET[$key]) ? $_GET[$key] =0:0;

*之后您可以自由使用变量(var1,var2,var3 ...等),

PS:接收JSON对象的函数应该更好(或带有分隔符的简单字符串(用于爆炸/内爆);

...欢迎更好的方法:)


更新:

使用 $_REQUEST 而不是 $_GET,这样你就可以覆盖 $_GET 和 $_POST 变量。

!isset($_REQUEST[$key]) ? $_REQUEST[$key] =0: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;
半枫 2024-10-05 12:09:50

为什么不创建一个函数来执行此操作,将要检查的变量转换为实际变量,例如。

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

然后你做 _FX('param') == '123',只是一个想法

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

青萝楚歌 2024-10-05 12:09:50

我一直使用自己有用的函数 exst() 来自动声明变量。

例子 -

$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;
}

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;
}
撕心裂肺的伤痛 2024-10-05 12:09:50
<?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) 
<?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) 
晨敛清荷 2024-10-05 12:09:50

这与已接受的答案类似,但使用 in_array 代替。在这种情况下我更喜欢使用 empty()。我还建议使用 PHP 5.4.0+ 中提供的新速记数组声明。

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

这是一个用于一次检查多个值的函数。

$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;
}

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;
}
旧瑾黎汐 2024-10-05 12:09:50

好吧,您只需使用 if($_GET['myvar'] == 'something') 就可以了,因为该条件假定该变量也存在。如果不是,表达式也将导致 false

我认为在上面的条件语句中执行此操作是可以的。确实没有造成任何伤害。

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.

暗喜 2024-10-05 12:09:50

没有官方参考,但当我尝试这个时它有效:

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

No official reference but it worked when I tried this:

if (isset($_GET['myvar']) == 'something')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文