How to Use the @ Sign in PHP

In PHP, the @ sign is applied for controlling errors. In other words, it is an error control operator.

Here, we will check out two options of using this sign as an error control operator.

Before starting to use the @ sign as an error control operator, consider that it doesn’t make errors disappear. They just get hidden. Also, it might make debugging more difficult as you won’t be able to see what’s wrong with the code.

Option 1

Once the @ sign is added before an expression, error messages that might be created by that expression are ignored.

In case the track_errors feature is activated, an error message will be created by that expression and saved inside the $php_errormsg variable.

That variable is overwritten every time.

Let’s see an example:

<?php

// File error
($file = @file('non_existent_file')) or die("Failed in opening the file.");

// It is applied for expression
$value = @$cache['key'];

// It won’t show notice in case the index $key doesn't exist.

?>

The output will be:

 Failed in opening the file.

Option 2

Let’s see another usage example of the @ sign:

<?php

// Statement 1
$result = @$hello['123'];

// Statement 2
$result = $hello['123'];

?>

Only statement 1 will not throw any error but statement 2 will be run by it, and the notice message will be displayed like this:

PHP Notice: Undefined variable: hello.