首页 > 解决方案 > What is the php function to simultaneously check the existence of a $_GET parameter and access its value

问题描述

In PHP, to avoid Undefined Index errors, one can write

if(isset $_GET['var1'] && $_GET['var1'] == 'My Matching Text'){
    //do stuff
}

But I remember using a function (or language construct) that I think would allow something like this:

if([THE FUNCTION I'M LOOKING FOR]($_GET['var1']) == 'My Matching Text'){
    //do stuff
}

What is this function whose name I have forgotten?

标签: phpsuperglobals

解决方案


你在考虑filter_input功能吗?

if (filter_input(INPUT_GET, 'var1') == 'My Matching Text') {
    //do stuff
}

它需要第三个参数,您可以在其中指定不同的过滤器类型,这很有用。默认类型根本不过滤,但它会在没有未定义索引通知的情况下返回值(如果未设置键,则返回 null)。

我不知道这在性能方面与使用 null 合并运算符(如其他答案所示)相比如何,但我认为这个函数调用会贵一些,所以除非你将使用其中一个过滤器。


推荐阅读