60

I've seen function calls preceded with an at symbol to switch off warnings. Today I was skimming some code and found this:

$hn = @$_POST['hn'];

What good will it do here?

2

5 Answers 5

78

The @ is the error suppression operator in PHP.

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

See:

Update:

In your example, it is used before the variable name to avoid the E_NOTICE error there. If in the $_POST array, the hn key is not set; it will throw an E_NOTICE message, but @ is used there to avoid that E_NOTICE.

Note that you can also put this line on top of your script to avoid an E_NOTICE error:

error_reporting(E_ALL ^ E_NOTICE);
5
  • But it is used before a variable name not a function. Aug 23, 2010 at 20:45
  • if hn is not set in $_POST, it will throw a notice (Notice: undefined index...). @ will suppress that notice. But using @ is just wrong. Aug 23, 2010 at 20:49
  • Understand now. Thank you Sarfaraz. Hope your people could put the flood behind them soon. Aug 23, 2010 at 20:57
  • "PHP6 Note" —— that makes no sense.
    – salathe
    Aug 23, 2010 at 21:25
  • 2
    Something that others forgot to mention is that besides ignoring the NOTICE, the variable will be set to NULL.
    – Yani
    Jul 18, 2019 at 10:19
11

It won't throw a warning if $_POST['hn'] is not set.

0
7

All that means is that, if $_POST['hn'] is not defined, then instead of throwing an error or warning, PHP will just assign NULL to $hn.

0
3

It suppresses warnings if $_POST['something'] is not defined.

2

I'm answering 11 years later for completeness regarding modern php.

Since php 7.0, the null coalescing operator is a more straightforward alternative to silencing warnings in that case. The ?? operator was designed (among other things) for that purpose.

Without @, a warning is shown:

$ php -r 'var_dump($_POST["hn"]);'
PHP Warning:  Undefined array key "hn" in Command line code on line 1
NULL

The output with silencing warnings (@):

$ php -r 'var_dump(@$_POST["hn"]);'
NULL

Obtaining the same result with the modern null coalescing operator (??):

$ php -r 'var_dump($_POST["hn"] ?? null);'
NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.