- Avoiding undefined index / offset errors in PHP.
- What is an index?
- Undefined offset and index errors.
- $_POST, $_GET and $_SESSION.
- Avoiding index errors.
- What is an Undefined Index PHP Error? How to Fix It?
- Basics to Advanced — Learn It All!
- What Is an Undefined Index PHP Error?
- Code:
- Result:
- How to Ignore PHP Notice: Undefined Index?
- 1. Adding Code at the Top of the Page
- Code:
- 2. Changes in php.ini
- Learn 15+ In-Demand Tools and Skills!
- How to Fix the PHP Notice: Undefined Index?
- Undefined Index in PHP $_GET
- Code:
- Code:
- Result:
- Here’s How to Land a Top Software Developer Job
- Code:
- Result:
- Code:
- Result:
- Code:
- Result:
- Code:
- Designing a Social Media App Like Instagram
- Code:
- Result:
- Code:
- Result:
- Conclusion
- Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
- About the Author
- Recommended Programs
Avoiding undefined index / offset errors in PHP.
This is a PHP tutorial on how to “fix” undefined index and undefined offset errors.
These are some of the most common notices that a beginner PHP developer will come across. However, there are two simple ways to avoid them.
What is an index?
Firstly, you will need to understand what an index is.
When you add an element to array, PHP will automatically map that element to an index number.
For example, if you add an element to an empty array, PHP will give it the index “0“. If you add another element after that, it will be given the index “1“.
This index acts as an identifier that allows you to interact with the element in question. Without array indexes, we would be unable to keep track of which element is which.
Take the following array as an example.
//Example array $animals = array( 0 => 'Cat', 1 => 'Dog', 2 => 'Bird' );
As you can see, Cat has the index “0” and Dog has the index “1“. If I want to print the word “Cat” out onto the page, I will need to access the “Cat” element via its array index.
//We know that "Cat" is at index 0. echo $animals[0]; //Prints out "Cat"
As you can see, we were able to access the “Cat” element by specifying the index “0“.
Similarly, if we want to print out the word “Dog”, then we can access it via the index “1“.
//Print out "Dog" echo $animals[1];
If we want to delete the “Dog” element from our PHP array, then we can do the following.
//Deleting "Dog" from our array. unset($animals[1]);
The unset function will remove the element in question. This means that it will no longer exist.
Undefined offset and index errors.
An undefined offset notice will occur if you attempt to access an index that does not exist.
This is where you’ll encounter nasty errors such as the following.
Notice: Undefined offset: 1 in /path/to/file.php on line 2
Or, if you are using array keys instead of numerical indexes.
Notice: Undefined index: test in /path/to/file.php on line 2
PHP will display these notices if you attempt to access an array index that does not exist.
Although it is not a fatal error and the execution of your script will continue, these kind of notices tend to cause bugs that can lead to other issues.
$_POST, $_GET and $_SESSION.
A lot of beginner PHP developers fail to realize that $_POST, $_GET, $_SESSION, $_FILES, $_COOKIE, $_SERVER and $_REQUEST are all predefined arrays.
These are what we call superglobal variables.
In other words, they exist by default. Furthermore, developers should treat them like regular arrays.
When you access a GET variable in PHP, what you’re actually doing is accessing a GET variable that has been neatly packaged into an array called $_GET.
//$_GET is actually an array echo $_GET['test'];
In the above piece of code, you are accessing an array element with the index “test”.
Avoiding index errors.
To avoid these errors, you can use two different methods.
The first method involves using the isset function, which checks to see if a variable exists.
//Check if the index "test" exists before accessing it. if(isset($_GET['test'])) < //It exists. We can now use it. echo $_GET['test']; >else < //It does not exist. >
The second method involves using the function array_key_exists, which specifically checks to see if an array index exists.
if(array_key_exists('test', $_GET)) < //It exists echo $_GET['test']; >else < //It does not exist >
When you are dealing with GET variables and POST variables, you should never assume that they exist. This is because they are external variables.
In other words, they come from the client.
For example, a hacker can remove a GET variable or rename it. Similarly, an end user can inadvertently remove a GET variable by mistake while they are trying to copy and paste a URL.
Someone with a basic knowledge of HTML can delete form elements using the Inspect Element tool. As a result, you cannot assume that a POST variable will always exist either.
What is an Undefined Index PHP Error? How to Fix It?
PHP is a widely used scripting language that is mainly used for web development purposes. It is a scripting language and finds application in automating tasks that would otherwise be impossible to implement with just human intervention. Being a server-side language, it primarily takes care of things at the server’s end. Launched in 1995 for public use, it has remained a popular choice among web developers since then.
Programming is a tricky business. It is pretty normal to stumble upon errors and warnings while making a program. The same happens a lot to PHP developers, like when they face an Undefined index in PHP. However, such errors are not hard to deal with with a little bit of knowledge and guidance.
Basics to Advanced — Learn It All!
What Is an Undefined Index PHP Error?
Websites often use forms to collect data from visitors. PHP uses $GET and $POST methods for such data collection. This data is collected and saved in variables that are used by the website to work and serve the visitor further. Many a time, some fields are left blank by the user. But the website tries to refer to these fields for proceeding further. That means the PHP code tries to get the value of the field that no one has defined and thus does not exist. Quite expectedly, it does not work and raises a notice called Undefined Index in PHP.
Code:
Result:
You can fix it using the isset() function, which we will discuss further in the upcoming sections.
Undefined Index is a notice in PHP, and it is a choice of the developer to either ignore it or fix it.
How to Ignore PHP Notice: Undefined Index?
Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php.ini file.
1. Adding Code at the Top of the Page
A simple way to ask PHP to disable reporting of notices is to put a line of code at the beginning of the PHP page.
Code:
Or you can add the following code which stops all the error reporting,
2. Changes in php.ini
Php.ini is a configuration file and is essential for all the programs running on PHP. Open this file and find the field error_reporting. The easiest way is to use the ctrl + F shortcut key. By default, error reporting is set to E_ALL. That means all errors are reported. Change this to E_ALL & ~E_NOTICE. It means all errors except for the notices will now be reported.
Learn 15+ In-Demand Tools and Skills!
How to Fix the PHP Notice: Undefined Index?
We know the cause of the error. It occurs when we use $_GET and $_POST methods to get input, but we reference it even when it has not been set. The solution simply is to check if it has been set before referencing.
We can use the isset() function, which checks if the variable ‘is set’ or not before referencing to them. Isset() function returns True or False depending on it.
Undefined Index in PHP $_GET
When using the $_GET method, the following code might show the notice Undefined index in PHP:
Code:
As we have not set any of these variables, this code shows the Undefined Index notice.
Change it to the following code to fix this issue:
Code:
$name = » John — This is our default name»;
$age = «10 — This is our default age. Let’s leave the grade blank.»;
Result:
Here’s How to Land a Top Software Developer Job
We can use a single line of code like this instead.
Code:
$name = isset($_GET[‘name’]) ? $_GET[‘name’]: “John- This is our default name”;
This approach also achieves the intended goal.
Result:
Notice: Undefined Variable
PHP shows this notice when we try to use a variable even before defining it.
Code:
Result:
It can be solved either by declaring a variable global and then using isset() to see if it is set or not. It can be echoed only if it has been set. Alternatively, we can use isset(X) ? Y to set a default.
Code:
Result:
We can set it after the isset() check like this.
Code:
$name= isset($name) ? $name:»Default»;
Designing a Social Media App Like Instagram
It shows Undefined Offset Notice in PHP when we are referring to a key in an array that has not been set for the array.
Code:
$nameArray = array(1=>’one’, 2=>’two’, 4=>’four’);
Result:
It might show an undefined array key warning for some. It means the same thing that you are trying to access an undefined array key.
It can be solved similarly like the last two cases by using isset(), arrayexists() or empty() function.
Code:
$nameArray = array(1=>’one’, 2=>’two’, 4=>’four’);
echo ‘
using array_key_exists
‘;
echo array_key_exists(3, $nameArray);
echo array_key_exists(2, $nameArray);
Result:
Learn right from the basics of JavaScript to advanced concepts of Angular, Spring Boot, Hibernate, JSPs, MVC, etc. Enroll in our PGP in Full Stack Web Development today!
Conclusion
In this article, we learned about the undefined index in PHP. However, it is just one of the many errors, warnings, and notices that a PHP developer has to deal with. If you are looking to make a career out of developing web applications and handling such errors, Simplilearn is offering a Post Graduate Program in Full stack Web Development, in partnership with Caltech CTME. Simplilearn is the world’s #1 online Bootcamp that has helped advance 2,000,000 careers through collaboration with World’s top-ranking universities.
Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
Name | Date | Place | |
---|---|---|---|
Post Graduate Program in Full Stack Web Development | Cohort starts on 15th Aug 2023, Weekend batch | Your City | View Details |
Post Graduate Program in Full Stack Web Development | Cohort starts on 12th Sep 2023, Weekend batch | Your City | View Details |
Post Graduate Program in Full Stack Web Development | Cohort starts on 10th Oct 2023, Weekend batch | Your City | View Details |
About the Author
Ravikiran A S
Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.
Recommended Programs
Post Graduate Program in Full Stack Web Development
Full Stack Web Developer — MEAN Stack
Automation Testing Masters Program
*Lifetime access to high-quality, self-paced e-learning content.