PHP 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, this is from the PDF. However, they did not indicate why they used '' for question1 in the if statement, but without the quotation marks in the echo statement.

In short: why $ _POST ['question1'] has '' in the if statement and why $ _POST [question1] doesn't have an echo in the expression. They are one and the same variable. Thanks.

+4
source share
2 answers

Always use quotation marks (for string keys) if inside a string with double quotes. See the 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; 
+3
source

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

Here are the finer details:

  • When an array key begins with an alphabetical character, PHP will "understand" that you want to put single quotes if you did not put them. Thus, $var[key] will be interpreted as $var['key'] .
  • Inside double-quoted strings are volume array variables with curly braces to avoid problems. This works in HEREDOCS! echo "Your ID is {$user['id']}." .
  • You can use double quotes, but it is not recommended if you do not perform variable interpolation, i.e. $var["someKey$num"] . Even so, it is better to use $var['someKey'.$num] or $var["someKey{$num}"] .
0
source

Source: https://habr.com/ru/post/1433158/


All Articles