0

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

This is strange but I am posting an input using the $_POST method which is below:

$c = count($_POST['gridValues']);

But the problem is that I am receiving an error stating:

Notice: Undefined index: gridValues in /web/stud/..../ on line 40 (which is line above)

How come I am receiving this error because the $_POST method is definitly correct?

Below is the whole code:

<?php

ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_divisor', '1');
ini_set('session.gc_probability', '1');
ini_set('session.cookie_lifetime', '0');
require_once 'init.php'; 

 ini_set('display_errors',1); 
 error_reporting(E_ALL);


session_start();

?>

$i = 0;
$c = count($_POST['gridValues']);

for($i = 0;  $i < $c; $i++ ){

    switch ($_POST['gridValues'][$i]){

 case "3": 
    $selected_option = "A-C";
    break;

    case "4": 
    $selected_option = "A-D";
    break;

    case "5": 
    $selected_option = "A-E";
    break;
}
}
Community
  • 1
  • 1
user1723760
  • 1,157
  • 1
  • 9
  • 18
  • This might be helpful for you: http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12770836#12770836 – hakre Oct 09 '12 at 23:17

2 Answers2

2

You need to check if it is set first:

<?php

if(isset($_POST['gridValues'])) {
   $c = count($_POST['gridValues']);
}
?>
Kyle Hudson
  • 898
  • 1
  • 14
  • 26
  • but now I am getting `undefined variable: c ` error. Do I have to isset that as well? – user1723760 Oct 09 '12 at 23:19
  • $c would only be valid in the cope of the if statement. where one would assume is where you'd do things with values from $_POST['gridValues'] you probably need to move more code into the if block. – j_mcnally Oct 09 '12 at 23:24
0

There are a few ways to prevent a notice level message about an undefined variable.

  1. Put @ in front of the variable. ex: $c = @$_POST['gridValues'] This can be dangerous as you are explicitly telling it to ignore any problems with the variable. See the PHP manual for more info on @: http://php.net/manual/en/language.operators.errorcontrol.php

  2. Turn off (or change) error reporting. ex: ini_set('display_errors', 0);

  3. Check if the variable is defined before using it. ex:

    $c = '';
    if(!empty($_POST['gridValues'])){
        $c = count($_POST['gridValues']);
    }
    
Brett
  • 2,502
  • 19
  • 30