Jaasus
Jaasus

Reputation: 45

Unidentified index while echoing out else

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 :)

Upvotes: 0

Views: 77

Answers (1)

Phiter
Phiter

Reputation: 14982

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;

Upvotes: 2

Related Questions