PHP:检查变量是否存在,但是如果值等于某个值 [英] PHP: Check if variable exist but also if has a value equal to something

查看:932
本文介绍了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天全站免登陆