Question

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.

Was it helpful?

Solution

Try this:

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

OTHER TIPS

Yet another variation of the same answer, but shorter:

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

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'] : '';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top