When using an undefined constant, PHP will automatically assume a string was intended. [sic]
PHP assumes that you mean the name of the constant itself, just as if
you called it as a string
Example: https://3v4l.org/C7PgT
As noted in the PHP 7.x, it will result in an ERROR as opposed to a warning in future versions, so its use should be avoided in favor of using quoted strings
Why $foo[bar]
is wrong: [sic]
Always use quotes around a string literal array index. For example,
$foo['bar']
is correct, while $foo[bar]
is not.
The reason is that this code has an undefined constant (bar
) rather than a string ('bar'
- notice the quotes).
if there is no defined constant named bar
, then PHP will substitute in the string 'bar'
and use that.
This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.
When you used it within a double-quoted context ("$var"
), PHP's lexer automatically used the text within the brackets ($var[text]
) as a string.
Also PHP's lexer has issues when using array or objects within double quotes.
echo "value=$row['first_name']"; //results in a syntax error
Example: https://3v4l.org/K6fUd
To resolve this issue you would need to wrap your array with curly-brackets
echo "value={$row['first_name']}";
Excample: https://3v4l.org/aQ1sJ
Instead I highly suggest conforming to single quotes for all PHP output to save you from having to read between different syntax and HTML syntax uniformity.
foreach ($results as $row) {
echo '<form action="/test.php" method="post">
<input type="text" name="first_name" value="' . $row['first_name'] . '">
<input type="submit" value="Click"><br>
</form>';
}
Alternatively using HEREDOC or NOWDOC depending on desired output.
foreach ($rows as $row) {
echo <<<EOT
value="{$row['first_name']}"
EOT;
}
Example (including HEREDOC): https://3v4l.org/7K5ap
My preferred method is to ensure all HTML syntax is output directly or to the output buffer. As it allows for most IDE's, such as PHPStorm, to automatically distinguish it as HTML and not PHP code, to ensure HTML syntax is valid and matches with other tags.
<?php foreach ($results as $row) { ?>
<form action="/test.php" method="post">
<input type="text" name="first_name" value="<?php echo $row['first_name']; ?>">
<input type="submit" value="Click"><br>
</form>
<?php } ?>