Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch this error: "Notice: Undefined offset: 0"

I want to catch this error:

$a[1] = 'jfksjfks'; try {       $b = $a[0]; } catch (\Exception $e) {       echo "jsdlkjflsjfkjl"; } 

Edit: in fact, I got this error on the following line: $parse = $xml->children[0]->children[0]->toArray();

like image 770
meotimdihia Avatar asked Mar 21 '11 04:03

meotimdihia


People also ask

How do you fix Undefined offset?

Fix Notice: Undefined offset by using isset() Function Check the value of offset array with function isset(), empty(), and array_key_exists() to check if key exist or not.

How do I fix Undefined offset 0 in PHP?

You can do an isset() : if(isset($array[0])){ echo $array[0]; } else { //some error? }

What is an undefined offset?

The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.

How define offset in PHP?

It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.


1 Answers

You need to define your custom error handler like:

<?php  set_error_handler('exceptions_error_handler');  function exceptions_error_handler($severity, $message, $filename, $lineno) {   if (error_reporting() == 0) {     return;   }   if (error_reporting() & $severity) {     throw new ErrorException($message, 0, $severity, $filename, $lineno);   } }  $a[1] = 'jfksjfks'; try {       $b = $a[0]; } catch (Exception $e) {       echo "jsdlkjflsjfkjl"; } 
like image 173
zerkms Avatar answered Sep 25 '22 17:09

zerkms