Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's square brackets: when to put quotes and when not?

<html>
<head><title></title></head>
<body>
<?php
if (isset ($_POST['posted'])) {
if ($_POST['question1'] == "Lisbon") {
  echo "You are correct, $_POST[question1] is the right answer<hr>";
}

if ($_POST['question1'] != "Lisbon") {
  echo "You are incorrect, $_POST[question1] is not. the right answer<hr>";
}
}
?>
<form method="POST" action="quiz.php">
<input type="hidden" name="posted" value="true">
What is the capital of Portugal?
<br>
<br>
<input name=''question1" type=''radio" value=''Porto''>
Porto
<br>
<input name=''question1" type="radio" value=''Lisbon''>
Lisbon
<br>
<input name="question1" type="radio" value=''Madrid''>
Madrid
<br>
<br>
<input type=''submit''>
</form>
</body>
</html>

This is the whole part, it's from a PDF. Thing is though, they didn't specified why they used ' ' for the question1 in the if statement but no quotes in the echo statement.

In a nutshell: why $_POST['question1'] has ' ' in the if statement and why $_POST[question1] doesn't have in the echo statement. They are the same variable. Thank you.

like image 856
erasmus77 Avatar asked Oct 06 '22 16:10

erasmus77


1 Answers

Always use quotes (for string keys), unless inside a double quoted string. See the string parsing section of the manual.

$juices = array("apple", "orange", "koolaid1" => "purple");

echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some juice made of $juice[0]s.".PHP_EOL; // Won't work
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
like image 185
Matthew Avatar answered Oct 12 '22 21:10

Matthew