Notice: Undefined index: name in test.php on line 3 Error On PHP 7

PHP hello world
Photo by KOBU Agency on Unsplash

Writing a PHP application is so simple and fun because the PHP is interpreted, you don’t need to compile first your program to run it. As soon as you save the project file you are working on, you can just execute from the browser.

Consider this PHP file named test.php below

<?php
$array = array();
echo $array['name'];

For really beginners PHP Programmers, some little error warning can be frustrating because most of them don't know how to handle and overcome the error.

The error Notice: Undefined index: name in test.php on line 3 from the code above is telling you two possible situations:
the variable doesn’t have the name key,
the variable is empty, so it doesn’t the name key

Solution

Before accessing a variable key that may not exist, or the array itself is a Null or empty, you can first check the availability of the key using the EMPTY function.

From the code example above that shows error notification, you can fix the problem so that the notice warning disappears using this code below.

<?php
$array = array();
echo empty($array['name'])?'':$array['name'];

When you have an undefined index, it means that you access an Array that doesn't have the element you are trying to access using the key you are providing.

This error notice is really common to appear especially if you are getting data from the database, because the database is really flexible, the column name changes, the row is truncated or many more factors that can lead into empty results. So then the array variable doesn’t have the key that used to have it previously.

Popular posts from this blog

Spring Kafka - how to use ReplyingKafkaTemplate send and reply synchronously

How To Connect SSH Using PEM Certificate On Windows

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

Flutter Button With Left Align Text and Icon

How To Create Spring Boot Project Using Netbeans