Question

Can I use @ instead of isset to assign or test superglobal variable ?

Use this :

$foo = intval(@$_POST['bar']);

Instead of this :

$foo = isset($_POST['bar']) ? intval($_POST['bar']) : 0;

works without generate a notice but maybe for some reasons, the use of isset is better than @ ?

Was it helpful?

Solution

isset with the ternary operator would be cleaner and easier to read. Error suppression on the other hand, has some overhead costs:

I first built a simple test that would loop a million times accessing a variable with and without the suppression operator prepended. The differences were small, yet noticeable. Using the suppression operator ended up taking 40% longer to execute.

Sources:

http://seanmonstar.com/post/909029460/php-error-suppression-performance http://www.lunawebs.com/blog/2010/06/07/another-look-at-php-error-supression-performance/

OTHER TIPS

There's an alternative to using @ for those of us who are tired of using isset() before pulling the value:

function iisset(&$var, $default = null) {
     return isset($var) ? $var : $default;
}

There is no notice generated for passing a non-existent array index as a reference. So for your example you would use:

$foo = intval(iisset($_POST['bar'], 0));

I wish PHP had a function like this built-in. The amount of isset checks followed immediately by the retrieval of that array index is so common that without a function like this there is a ridiculous amount of extra code.

Update:

PHP 7 now has a built-in operator known as the null coalesce operator:

$foo = intval($_POST['bar'] ?? 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top