1

I have a device that sends data to url, depending on situations 3 sometimes 4 parameters are received, when i try to get data for 4th parameter using

$a = $_GET["xyz"];

in the case when "xyz" does not exist the function

_GET['xyz'];

returns undefined. i tried using try catch and initialized $a to a empty string in catch part but it did not work either. How can that undefined exception be handled?

halfer
  • 19,824
  • 17
  • 99
  • 186
mushahid
  • 504
  • 5
  • 21

4 Answers4

2

isset

  if(isset($_GET["xyz"])) {
        $a = $_GET["xyz"];
  }
smarber
  • 4,829
  • 7
  • 37
  • 78
1

If you want to check if a parameter is passed in through the URL, you can use isset()

http://php.net/manual/en/function.isset.php

This will check to see if the parameter exists

// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo "This var is set so I will print.";
}
1

You can use ternary operator

$a=(isset($_GET["xyz"]))?$_GET["xyz"]:'';   
Pranay Aher
  • 444
  • 4
  • 11
1

To handle such errors, you should use php's library function,

set_error_handler

On having error such as undefined index, undefined variable etc.. will be handle by handleError function.

public function handleError($code,$message,$file,$line){
    // handling 
}

All the Best !!

Sanjay Mohnani
  • 990
  • 7
  • 18