Skip to content
Fix Code Error

“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

March 13, 2021 by Code Error
Posted By: Anonymous

I’m running a PHP script and continue to receive errors like:

Notice: Undefined variable: my_variable_name in C:wampwwwmypathindex.php on line 10

Notice: Undefined index: my_index C:wampwwwmypathindex.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:

  • What can be done about repetitive questions?
  • Do “reference questions” make sense?

Solution

Notice: Undefined variable

From the vast wisdom of the 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 security risk with register_globals turned on. 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. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.

From 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 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 advises to allow during development.

Ways to deal with the issue:

  1. Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !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 null coalesce operator:

    // Null coalesce operator - No need to explicitly initialize the variable.
    $value = $_POST['value'] ?? '';
    
  2. Set a 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)
    
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    error_reporting( error_reporting() & ~E_NOTICE )
    
  4. Suppress the error with the @ operator.

Note: It’s strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset

This notice appears when you (or PHP) try to access an undefined index of an array.

Ways to deal with the issue:

  1. Check if the index exists before you access it. For this you can use isset() or 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'] : '';
    
  2. The language construct 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

$_POST / $_GET / $_SESSION variable

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 session_start() and that the index also exists.

Also note that all 3 variables are superglobals and are uppercase.

Related:

  • Notice: Undefined variable
  • Notice: Undefined Index
Answered By: Anonymous

Related Articles

  • PHP: How to use array_filter() to filter array keys?
  • PHP parse/syntax errors; and how to solve them
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Reference — What does this symbol mean in PHP?
  • How to prevent scrolling the whole page?
  • error LNK2005: ✘✘✘ already defined in…
  • What is a NullReferenceException, and how do I fix it?
  • Ukkonen's suffix tree algorithm in plain English
  • Laravel + Vue.js. Load more data when i click on the button
  • How does PHP 'foreach' actually work?
  • What is your most productive shortcut with Vim?
  • The definitive guide to form-based website authentication
  • What are the undocumented features and limitations…
  • Logging best practices
  • Can't install via pip because of egg_info error
  • "Thinking in AngularJS" if I have a jQuery background?
  • How can I exclude all "permission denied" messages…
  • What is the incentive for curl to release the…
  • What are the real-world strengths and weaknesses of…
  • laravel vuejs/axios put request Formdata is empty
  • Polymer dom-repeat not rendering changes with…
  • Why does C++ code for testing the Collatz conjecture…
  • How to return grandchilds names for each person in array JS?
  • useEffect Error: Minified React error #321 (GTM…
  • How to echo with different colors in the Windows…
  • What does this symbol mean in JavaScript?
  • Database development mistakes made by application developers
  • Reference - What does this regex mean?
  • How to create a search filter using Vue js from API Data?
  • Proper error handling with Svelte from API (Rails)
  • What does "Fatal error: Unexpectedly found nil while…
  • Handling errors with the (now default) Ember Data…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How to scroll to bottom of div when new elements are added
  • How to pass the id value of an url with axios and…
  • Echo a blank (empty) line to the console from a…
  • Start redis-server with config file
  • How to properly do JSON API GET requests and assign…
  • How to create websockets server in PHP
  • Output not incrementing correctly - C++
  • Memcached vs. Redis?
  • Ember.JS: Observing @each, but just iterating over…
  • For-each over an array in JavaScript
  • How to extract random rows from a numpy array within…
  • Smart way to truncate long strings
  • ListView refreshes only on scroll up and down
  • Removing double quotes from variables in batch file…
  • Upload video files via PHP and save them in…
  • Limit array of dom-repeat within iron-list
  • Node.js Best Practice Exception Handling
  • Am I paranoid? "Brutally" big Polymer website after…
  • Python timedelta in years
  • How can I find the product GUID of an installed MSI setup?
  • commandButton/commandLink/ajax action/listener…
  • Getting started with Haskell
  • Java 8: Difference between two LocalDateTime in…
  • What is the difference between Amazon SNS and Amazon SQS?
  • how to make a conditional multilevel menu with vue.js?
  • ExpressJS How to structure an application?
  • What's the best way of scraping data from a website?
  • Where and why do I have to put the "template" and…
  • Backbone.js - Should nested Views maintain…
  • How to configure Ubuntu as router in Vagrant
  • How do you parse and process HTML/XML in PHP?
  • The mysql extension is deprecated and will be…
  • How can I fix MySQL error #1064?
  • Print array elements on separate lines in Bash?
  • What's the difference between eval, exec, and compile?
  • problem with client server unix domain stream…
  • Using Auto Layout in UITableView for dynamic cell…
  • #define macro for debug printing in C?
  • data.table vs dplyr: can one do something well the…
  • NextJS getServerSideProps pass data to Page Class
  • Vue JS: Open Menu Component with Button, Close with…
  • Error message "Forbidden You don't have permission…
  • Ember.js -- How do I target outlets in…
  • Form field border-radius is not working only on the…
  • SQL query return data from multiple tables
  • Apache server keeps crashing, "caught SIGTERM,…
  • Elasticsearch inline string replace seems to do nothing
  • What is the copy-and-swap idiom?
  • After a little scroll, the sticky navbar just is not…
  • Backbone.js Backbone.wrapError function
  • Best practice multi language website
  • How do I count unique visitors to my site?
  • AppCompat v7 r21 returning error in values.xml?
  • Getting a "TypeError" when trying to validate a form
  • display other inputs based on the value of another…
  • What are type hints in Python 3.5?
  • How to reverse apply a stash?
  • Understanding REST: Verbs, error codes, and authentication
  • What is an optional value in Swift?
  • How to VueJS router-link active style
  • vue / vuetify dynamically modify v-text-field properties
  • Saving multiple data dynamic form in Laravel 5.1 and Vue JS
  • EntityFramework core - Update a collection of data…
  • How to create an empty array in PHP with predefined size?
  • XMLHttpRequest cannot load ✘✘✘ No…
  • How can I manually compile a svelte component down…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

JavaScript chop/slice/trim off last character in string

Next Post:

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error