erasmus77
erasmus77

Reputation: 327

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.

Upvotes: 5

Views: 3455

Answers (2)

dotancohen
dotancohen

Reputation: 31471

The characters of the array key are literals, so text should have single quotes. Integer keys should never have quotes.

Here are the finer details:

  • When the array key starts with an alphabetical character, PHP will "understand" that you meant to put single quotes if you didn't put them. So $var[key] will be interpreted as $var['key'].
  • Inside double-quoted strings, surround array variables with curly brackets to avoid issues. This works in HEREDOCS too! echo "Your ID is {$user['id']}.".
  • You can use double quotes, but it is recommended not to unless you are doing variable interpolation, i.e. $var["someKey$num"]. Even in this case, better to use $var['someKey'.$num] or $var["someKey{$num}"].

Upvotes: 0

Matthew
Matthew

Reputation: 48284

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;

Upvotes: 4

Related Questions