“Notice: Undefined variable”, Undefined index”, and ,“Undefined offset” using PHP
PHP is a web-focussed programming language, so processing user data is a frequent activity. In such processing it is common to check for something's existence, and if it doesn't exist, use a default value.
What the problem is ?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix them. This is also a Community Wiki, so everyone is invited to participate adding to and maintaining this list.
This means that you could use only empty()
to determine if the variable is set, and in addition it checks the variable against the following, 0
, 0.0
, ""
, "0"
, null
, false
or []
.
Notice: Undefined variable
This means that you could use only empty()
to determine if the variable is set, and in addition it checks the variable against the following, 0
, 0.0
, ""
, "0"
, null
, false
or []
.
Example:
$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
echo (!isset($v) || $v == false) ? 'true ' : 'false';
echo ' ' . (empty($v) ? 'true' : 'false');
echo "\n";
});
ALTERNATIVE SOLUTIONS -
/Initializing variable
$value = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0 When you want to add numbers later
//isset()
$value = isset($_POST['value']) ? $_POST['value'] : '';
//empty()
$value = !empty($_POST['value']) ? $_POST['value'] : '';
Null coalesce operator
// Null coalesce operator - No need to explicitly initialize the variable.
$value = $_POST['value'] ?? '';
This function can be used for defining your own way of handling errors
during runtime, for example in applications in which you need to do
cleanup of data/files when a critical error happens, or when you need
to trigger an error under certain conditions
Set error handler
set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:
error_reporting( error_reporting() & ~E_NOTICE )
Now ,Suppress the error with the @ operator.
Notice: Undefined index / Undefined offset
Check if the index exists -
//isset() $value = isset($array['my_index']) ? $array['my_index'] : ''; //array_key_exists() $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
list()
generate this when it try to access an array index that does not exist:
list($a, $b) = array(0 => 'a');
//or
list($one, $two) = explode(',', 'test string');
$_POST / $_GET / $_SESSION variable
// recommended solution for recent PHP versions $user_name = $_SESSION['user_name'] ?? ''; // pre-7 PHP versions $user_name = ''; if (!empty($_SESSION['user_name'])) { $user_name = $_SESSION['user_name']; }
or, as a quick and dirty solution:
// not the best solution, but works // in your php setting use, it helps hiding site wide notices error_reporting(E_ALL ^ E_NOTICE);
0 comments:
Post a Comment