0

I'm new to PHP and i've been learning PhP like a week ago so please bear with me.

While i was trying to echo out an else statement if any variable in the POST request is different or not set.

<form action="process.php" method="POST">
<p> <input type="radio" name="language" value="PHP"> PHP <br>
<input type="radio" name="language" value="RUBY"> RUBY <br>
<input type="radio" name="language" value="HTML"> HTML  <br>
 </p>
<input type="Submit" value="Submit">
</form>

process.php

<?php
$lang = $_POST['language'];
if (isset($lang)) {
 echo $lang;
}
else {
 echo 'Buzz off';
}

?>

While its showing error like :

Notice: Undefined index: language in /Applications/XAMPP/xamppfiles/htdocs/process.php on line 2

Please help :)

Phiter
  • 14,570
  • 14
  • 50
  • 84
Jaasus
  • 45
  • 4
  • so, this going to be voted out as a typo also? – Funk Forty Niner Mar 20 '18 at 18:04
  • Yeah I think they'll downvote it for being a typo. I don't think people know what a typo is anymore. At most, this should be considered a duplicate of that `Undefined index` question. – Phiter Mar 20 '18 at 18:07
  • @Phiter right... [deja vue?](https://stackoverflow.com/q/49391045/) - the "new" way now? if that's the way it's going to be, then Stack is on its way out. – Funk Forty Niner Mar 20 '18 at 18:08
  • Are you trying to visit `process.php` without submitting it from the form page? If so, you'll get the notice. You can fix it by doing what Phiter said. – Edward Mar 20 '18 at 18:08
  • @Phiter *heh* agreed man – Funk Forty Niner Mar 20 '18 at 18:10
  • While answering the question helps Jaasus with his specific problem, I still think it should be closed as duplicate of [this](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) or [that](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – masterfloda Mar 20 '18 at 19:35

1 Answers1

2

You're trying to get an undefined array index and put it into a variable, and this will throw an exception.
You should check if the array key isset before you try to put it in a variable, like this:

if ($_POST['language']) {
    $lang = $_POST['language'];
    echo $lang;
}
else {
    echo 'Buzz off';
}

If you are using PHP7, you can use the Null coalescing operator.

$lang = $_POST['language'] ?? 'Buzz off';
echo $lang;
Phiter
  • 14,570
  • 14
  • 50
  • 84