I'm a PhP n00b. I'm reading some online tutorial, but I've already a question (a very basic question, I suppose):

I don't understand why the following code works properly:

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <?php
            $userAgent = $_SERVER["HTTP_USER_AGENT"];
            echo "<p>This is my awesome User Agent: <b>\"$userAgent\"</b></p>";
        ?>
    </body>
</html>

and, instead, the following doesn't work although I protect the quotes inside the brackets:

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <?php
            echo "<p>This is my awesome User Agent: <b>$_SERVER[\"HTTP_USER_AGENT\"]</b></p>";
        ?>
    </body>
</html>

Thank you in advance.

有帮助吗?

解决方案

You've basically found an edge case of string interpolation. While alphanumeric array keys need to be quoted in PHP, in double-quoted strings they need to be unquoted:

echo "<p>This is my awesome User Agent: <b>$_SERVER[HTTP_USER_AGENT]</b></p>";

String parsing follows its own rules. In general, you can't drop random PHP code inside a string and get it executed.

其他提示

You could try one of these:

The curly bracket allows complex expressions within strings

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <?php
            echo "<p>This is my awesome User Agent: <b>{$_SERVER[\"HTTP_USER_AGENT\"]}</b></p>";
        ?>
    </body>
</html>

better yet, just use php for the piece you are outputting.

<html>
    <head>
        <title> My Firts PHP page </title>
    </head>
    <body>
        <p>This is my awesome User Agent: <b><?php echo $_SERVER["HTTP_USER_AGENT"]; ?></b></p>
    </body>
</html>

Wrong usage of escapinng quotes. See and test thhis:

echo "<p>This is my awesome User Agent: <b>". $_SERVER["HTTP_USER_AGENT"] ."</b></p>";

You can include a variable within the string like this:

echo "<p>This is my awesome User Agent: <b>{$_SERVER["HTTP_USER_AGENT"]}</b></p>";

It is nicer and cleaner if you used

echo "<p>This is my awesome User Agent: <b>". $_SERVER["HTTP_USER_AGENT"] ."</b></p>";

Or without single quotes in array key

echo "<p>This is my awesome User Agent: <b>$_SERVER[HTTP_USER_AGENT]</b></p>";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top