Hướng dẫn avoid undefined index php

Every time a POST value is not equal to the list of values set in an array will return: Undefined Index error, I made an if statement but is not working.

Here's the if statement:

 if ($products[$_POST['product']] == $_POST['product']) {
do everything;}
else {
echo "This item is not available";
}

EDIT2:

Seen the current situation avoiding the warning wont help much because I'm dealing with several factors, for example a list of items in a Shopping Cart, if the invalid product is not removed, it will be added to the shopping list session.

This is the full script:

<?php

session_start();

//Getting the list
 $_SESSION['list'] = isset($_SESSION['list']) ? $_SESSION['list'] : array();    

 //stock    
 $products = array(      
     'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,       
     'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,      
     'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,      
     'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,    
 );    

if( isset($_POST['product']) ){


     //Saving the stuff    
     $new_item = array(      
         'item' => $_POST['product'],       
         'quantity' => $_POST['quantity'],     
         'code' => $_POST['code'],      
         'price' => $products[$_POST['product']] * $_POST['quantity'],    

     );



    $new_product = true;    
    foreach($_SESSION['list'] as $key => $item) {      
        if ($item['item'] == $new_item['item']) {        
        $_SESSION['list'][$key]['quantity'] += $new_item['quantity'];        
        $_SESSION['list'][$key]['price'] = $products[$new_item['item']] * $new_item['quantity'];        
        $new_product = false;
        }    
    }   

    if ($new_product) {      
        $_SESSION['list'][] = $new_item;        
    }    

    /*if ($new_item['item'] != $products[$new_item['item']]) {
        echo "This item is not available";}*/

    //listing    
    echo  "<b>SHOPPING LIST</b></br>";    
    foreach($_SESSION['list'] as $key => $item) {       
        echo 'Product .'. $key. ' '. $item['item'], ' ', $item['quantity'], ' units: ', $item['price']. '<br />';    
        }

}

else {
echo "This item is not available";
}

echo "</br> <a href='index.html'>Return to index</a> </br>";

//Printing session
var_dump($_SESSION);

session_destroy();

?>

The isset() function does not check if a variable is defined.

It seems you've specifically stated that you're not looking for isset() in the question. I don't know why there are so many answers stating that isset() is the way to go, or why the accepted answer states that as well.

Nội dung chính

  • The isset() function does not check if a variable is defined.
  • So how do you actually check if a variable is defined? You check the defined variables.
  • What Is an Undefined Index PHP Error?
  • Code: 
  • How to Ignore PHP Notice: Undefined Index?
  • 1. Adding Code at the Top of the Page
  • 2. Changes in php.ini 
  • How to Fix the PHP Notice: Undefined Index?
  • Undefined Index in PHP $_GET

It's important to realize in programming that null is something. I don't know why it was decided that isset() would return false if the value is null.

To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars(). There is no equivalent to JavaScript's undefined (which is what was shown in the question, no jQuery being used there).

In the following example it will work the same way as JavaScript's undefined check.

$isset = isset($variable);
var_dump($isset); // false

But in this example, it won't work like JavaScript's undefined check.

$variable = null;
$isset = isset($variable);
var_dump($isset); // false

$variable is being defined as null, but the isset() call still fails.

So how do you actually check if a variable is defined? You check the defined variables.

Using get_defined_vars() will return an associative array with keys as variable names and values as the variable values. We still can't use isset(get_defined_vars()['variable']) here because the key could exist and the value still be null, so we have to use array_key_exists('variable', get_defined_vars()).

$variable = null;
$isset = array_key_exists('variable', get_defined_vars());
var_dump($isset); // true


$isset = array_key_exists('otherVariable', get_defined_vars());
var_dump($isset); // false

However, if you're finding that in your code you have to check for whether a variable has been defined or not, then you're likely doing something wrong. This is my personal belief as to why the core PHP developers left isset() to return false when something is null.

The ternary expression:

isset($extensionData['Calories']) ? $extensionData['Calories'] : ''

is OK when used stand-alone like this:

echo isset($extensionData['Calories']) ? $extensionData['Calories'] : '';

$tmp_var = isset($extensionData['Calories']) ? $extensionData['Calories'] : '';

return isset($extensionData['Calories']) ? $extensionData['Calories'] : '';

because it is equivalent to the expected:

if(isset($extensionData['Calories']))
{
    // use $extensionData['Calories']
}
else
{
    // use empty string ''
}

but, when used in string concatenation then you need parenthesis in order to confine the scope of the comparison so that the leading string is not part of the comparison

echo '<p>' . (isset($extensionData['Calories']) ? $extensionData['Calories'] : '') . '</p>';

Doing (wrong way):

echo '<p>' . isset($extensionData['Calories']) ? $extensionData['Calories'] : '' . '</p>';

is equivalent to

if('<p>' . isset($extensionData['Calories'])) // The leading string is used in the comparison and the result of isset() (boolean) is appended to the string so 100% of the time this example will be true because of how loose comparisons work
{
    echo $extensionData['Calories']; // Produces Undefined index error
}
else
{
    echo '' . '</p>';
}

In conclusion:

When in doubt, add parenthesis.

When not in doubt, add parenthesis anyways because the code will be more legible when you have to re-visit it in 6 months. Most text editors have parenthesis and bracket match highlighting so adding parenthesis is a very beneficial way to declare and later see the operation's intended behavior.

See Operator Precedence if you come across someone's cryptic code and need help figuring out what on Earth they were thinking and/or failed to consider.

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.

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: 

<?php

$name = $_GET['name'];

$age = $_GET['age'];

$grade = $_GET[‘grade’];

echo 'Name: '.$name;

echo '<br>Age: '.$age;

echo ‘<br>Grade: ‘.$grade;

?>

Result: 

Hướng dẫn avoid undefined index php

Notice: Undefined Variable

PHP shows this notice when we try to use a variable even before defining it.

Code:

<?php

$echo $name;

<?

Result:

undefined_Index_Php_4

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:

<?php

global $name;

if(isset($name))

{ echo $name;

}

?>

Result: 

undefined_Index_Php_5.

We can set it after the isset() check like this.

Code: 

<?php

$name= isset($name) ? $name:"Default";

echo $name;

?>

Result:

undefined_Index_Php_6.

Notice: Undefined Offset

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.

Here’s an example.

Code:

<?php

$nameArray = array(1=>'one', 2=>'two', 4=>'four');

echo $nameArray[3];

?>

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.

undefined_Index_Php_7.

It can be solved similarly like the last two cases by using isset(), arrayexists() or empty() function.

Code: 

<?php

$nameArray = array(1=>'one', 2=>'two', 4=>'four');

echo 'using isset()';

echo '<br>key 3 <br>';

if(isset($nameArray[3]))

    {echo  $nameArray[3];

    }

echo 'key 1 <br>';

if(isset($nameArray[1]))

    {echo $nameArray[1];

    }    

echo '<br> using array_key_exists <br>';

echo 'key 3 <br>';

echo array_key_exists(3, $nameArray);

echo '<br> key 2 <br>';

echo array_key_exists(2, $nameArray);

echo '<br>using empty <br>';

echo 'key 3 <br>';

if(!empty($nameArray[3]))

    {echo $nameArray[3]; }

echo '<br>using key 4 <br>';

if(!empty($nameArray[4]))

    {echo $nameArray[4]; }

?>

Result:

undefined_Index_Php_8.

Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

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.