0

I keep getting a undefined index error on my page. I have tried different things, but can't seem to get rid of it. I have a project where I have to create a simple area conversion running Server PHP Self.

<?php 
if ($_POST['number'] == "") {
    $number = '';
} else {
    $number = $_POST['number'];
 }
?>

 <form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
     <label>Please Select Area Conversion Method</label>
     <select name="con">
         <option selected="selected"></option>
         <option>Square Feet to Square Meters</option>
         <option>Square Yards to Square Meters</option>
         <option>Square Miles to Square Kilometers</option>
         <option>Square Meters to Square Feet</option>
         <option>Square Meters to Square Yards</option>
         <option>Square Kilometers to Square Miles</option>
     </select><br />
     <label>Input Number: </label>
     <input type="text" name="number" size="10" /><br />
     <input type="submit" value="Calculate" name="submit" />
 </form>

I have tried doing if isset and if empty, but can't seem to get rid of the undefined index error.

4
  • 4
    Could you also add the error? Commented Jul 5, 2012 at 19:35
  • Can you post how you implemented the IF statements Commented Jul 5, 2012 at 19:36
  • 1
    $number = isset( $_POST['number']) ? $_POST['number'] : ''; Commented Jul 5, 2012 at 19:39
  • possible duplicate of PHP: "Notice: Undefined variable" and "Notice: Undefined index" Commented Jul 5, 2012 at 20:57

3 Answers 3

1

Try this:

    <?php 
if (!isset($_POST['number'] || $_POST['number'] == "") {
 $number = '';
} else {
    $number = $_POST['number'];
 }
 ?>
Sign up to request clarification or add additional context in comments.

Comments

0

Yet another variation of the same answer, but shorter:

$number = empty($_POST['number']) ? '' : $_POST['number'] ;

Comments

0

There error is probably because the index number doesn't exist in $_POST.

Check to see that the $_POST['number'] exists before using it, or just check that $_POST is not empty before using indexes in it that may or may not be set.

if ( !empty($_POST) )
{
    if( $_POST['number'] == "" )
    // ...
}

or, if you are explicitly checking if 'number' is a blank string:

if( isset( $_POST['number'] ) && $_POST['number'] == "" )
{
    // ...

For your scenario, however, it might be best to just do something like:

$number = isset($_POST['number']) ? $_POST['number'] : '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.