PHP:检查变量是否存在以及是否具有等于某值的值 [英] PHP: Check if variable exist but also if has a value equal to something

查看:43
本文介绍了PHP:检查变量是否存在以及是否具有等于某值的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'):做某事

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

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

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

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

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

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

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

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.

更新

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

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
}

这篇关于PHP:检查变量是否存在以及是否具有等于某值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆