Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Notice: Undefined index although using try\catch

Tags:

php

try-catch

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?

like image 908
Asaf Nevo Avatar asked Aug 06 '13 13:08

Asaf Nevo


People also ask

How do I fix PHP Notice Undefined index?

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.

What causes Undefined index in PHP?

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.

How do you fix an undefined index error?

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.

How do I fix undefined variable error in PHP?

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.


2 Answers

use isset function to check if the variable is set or not:

if( isset($_GET['id'])){     $api = new api($_GET["id"]);     echo $api -> processRequest(); } 
like image 133
Nil'z Avatar answered Oct 07 '22 09:10

Nil'z


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.

like image 35
Markus Madeja Avatar answered Oct 07 '22 11:10

Markus Madeja