This is my try/catch block in PHP:
try { $api = new api($_GET["id"]); echo $api -> processRequest(); } catch (Exception $e) { $error = array("error" => $e->getMessage()); echo json_encode($error); }
When there is nothing in the $_GET["id"]
, I still get the notice error. How can I avoid getting this error?
Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php. ini file.
Notice Undefined Index in PHP is an error which occurs when we try to access the value or variable which does not even exist in reality. Undefined Index is the usual error that comes up when we try to access the variable which does not persist.
To resolve undefined index error, we make use of a function called isset() function in PHP. To ignore the undefined index error, we update the option error_reporting to ~E_NOTICE to disable the notice reporting.
Fix Notice: Undefined Variable by using isset() Function This notice occurs when you use any variable in your PHP code, which is not set. Solutions: To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.
use isset
function to check if the variable is set or not:
if( isset($_GET['id'])){ $api = new api($_GET["id"]); echo $api -> processRequest(); }
If you want a fast and "dirty" solution, you can use
$api = new api(@$_GET["id"]);
Edit:
Since PHP 7.0 there is a much better and accepted solution: using the null coalescing operator (??). With it you can shorten your code to
$api = new api($_GET["id"] ?? null);
and you don't get a notice because you defined what should happen in the case the variable is not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With