PHP:检查变量是否存在以及是否具有等于某值的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4007752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:43:34  来源:igfitidea点击:

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

phpvariablesif-statementisset

提问by Mariz Melo

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:

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

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

我正在做和认为的不是最好的方法:

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

if(isset($_GET['myvar']) && $_GET['myvar'] == '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 $myvarvariables.

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

采纳答案by mellowsoon

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.

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

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.

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

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
}

回答by James Hastings-Trew

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- nullwill be interpreted as equal to false.

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

回答by Nick

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

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

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

Output:

输出:

hello!

In general, the expression

一般来说,表达式

$a ?? $b

is equivalent to

相当于

isset($a) ? $a : $b

回答by Victor

As mellowsoon suggest, you might consider this approach:

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

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

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

回答by user2253362

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

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

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

回答by Sheldon Juncker

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

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

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

回答by Pekka

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

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

回答by Mariz Melo

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

感谢 Mellowsoon 和 Pekka,我在这里做了一些研究并得出了以下结论:

  • Check and declare each variable as null (if is the case) before start to use (as recommended):
  • 在开始使用之前(如推荐),检查并声明每个变量为 null(如果是这种情况):
!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),

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

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

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

... Better approaches are welcome :)

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



UPDATE:

更新:

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

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

!isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;

回答by windmaomao

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

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

回答by keithics

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