arrays - "Notice: Undefined variable", "Notice: Undefined index",
and "Notice: Undefined offset" using PHP
itemprop="text">
I'm running a PHP script and continue
to receive errors
like:
Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on
line 10
Notice: Undefined index: my_index
C:\wamp\www\mypath\index.php on line
11
Line 10 and 11
looks like this:
echo "My variable
value is: " . $my_variable_name;
echo "My index value is: " .
$my_array["my_index"];
What
is the meaning of these error messages?
Why do
they appear all of a sudden? I used to use this script for years and I've never had any
problem.
How do I fix
them?
/>
This is a General Reference question
for people to link to as duplicate, instead of having to explain the issue over and over
again. I feel this is necessary because most real-world answers on this issue are very
specific.
Related Meta
discussion:
itemprop="text">
From the
vast wisdom of the href="http://php.net/manual/en/language.variables.basics.php#example-112"
rel="noreferrer">PHP
Manual:
Relying on the default value of an uninitialized variable is problematic in the
case of including one file into another which uses the same variable name. It is also a
major rel="noreferrer">security risk with href="http://www.php.net/manual/en/ini.core.php#ini.register-globals"
rel="noreferrer">register_globals turned on. href="http://www.php.net/manual/en/errorfunc.constants.php#errorfunc.constants.errorlevels.e-notice"
rel="noreferrer">E_NOTICE level error is issued in case of working with
uninitialized variables, however not in the case of appending elements to the
uninitialized array. rel="noreferrer">isset() language construct can be used to detect if a
variable has been already initialized. Additionally and more ideal is the solution of
rel="noreferrer">empty() since it does not generate a warning or error
message if the variable is not initialized.
From href="http://php.net/manual/en/function.empty.php" rel="noreferrer">PHP
documentation:
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to
!isset($var) || $var
==
false.
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";
});
Test
the above snippet in the rel="noreferrer">3v4l.org online PHP
editor
Although PHP does
not require a variable declaration, it does recommend it in order to avoid some security
vulnerabilities or bugs where one would forget to give a value to a variable that will
be used later in the script. What PHP does in the case of undeclared variables is issue
a very low level error, E_NOTICE, one that is not even reported
by default, but the Manual href="http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting"
rel="noreferrer">advises to allow during
development.
Ways to deal with the
issue:
Recommended:
Declare your variables, for example when you try to append a string to an undefined
variable. Or use rel="noreferrer">isset() / href="http://php.net/manual/en/function.empty.php"
rel="noreferrer">!empty() to check if they are
declared before referencing them, as
in:
//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'] :
'';
This has become
much cleaner as of PHP 7.0, now you can use the href="https://wiki.php.net/rfc/isset_ternary" rel="noreferrer">null coalesce
operator:
// Null
coalesce operator - No need to explicitly initialize the
variable.
$value = $_POST['value'] ??
'';
Set a
rel="noreferrer">custom error handler for E_NOTICE and redirect the
messages away from the standard output (maybe to a log file):
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
)
Suppress
the error with the href="http://php.net/manual/en/language.operators.errorcontrol.php"
rel="noreferrer">@
operator.
Note:
It's strongly recommended to implement just point
1.
This notice appears
when you (or PHP) try to access an undefined index of an
array.
Ways to deal with the
issue:
Check
if the index exists before you access it. For this you can use href="http://php.net/manual/en/function.isset.php"
rel="noreferrer">isset() or href="http://php.net/manual/en/function.array-key-exists.php"
rel="noreferrer">array_key_exists():
//isset()
$value
= isset($array['my_index']) ? $array['my_index'] :
'';
//array_key_exists()
$value = array_key_exists('my_index',
$array) ? $array['my_index'] :
'';
The
language construct rel="noreferrer">list() may generate this when it
attempts to access an array index that does not
exist:
list($a, $b) =
array(0 => 'a');
//or
list($one, $two) = explode(',', 'test
string');
Two
variables are used to access two array elements, however there is only one array
element, index 0, so this will
generate:
Notice: Undefined offset:
1
The
notices above appear often when working with $_POST,
$_GET or $_SESSION. For
$_POST and $_GET you just have to
check if the index exists or not before you use them. For
$_SESSION you have to make sure you have the session started
with rel="noreferrer">session_start() and that the
index also exists.
Also note that all 3
variables are rel="noreferrer">superglobals and are
uppercase.
Related:
No comments:
Post a Comment