1

i'm doing this code from the book and i can't seem to get it to work

<html>
<head> <h3> <u> PHP tutorials  </u> </h3> </head>
<body>

<?php

$Texas = "large";
$RhodeIsland = "small";

$statement = "Texas";
echo "$statement is $($statement)<br>";

$statement = "RhodeIsland";
echo "$statement is $($statement)<br>";

?>
</body>
</html>

this is the output i keep getting:

Texas is $(Texas)

RhodeIsland is $(RhodeIsland)

instead of:

Texas is large

RhodeIsland is small

1
  • 1
    Try to avoid use of this (variable variable) if possible. Commented Apr 26, 2014 at 5:43

4 Answers 4

3

The syntax is : ${$variable_name}, not $($variable_name). You need to change your code to:

$statement = "Texas";
echo "$statement is ${$statement}<br>";

See the PHP manual documentation on Variable Variables for more information.

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

There you go:

 <?php

    $Texas = "large";
    $RhodeIsland = "small";

    $statement = "Texas";
    echo $statement." is ".${$statement}."<br />";

    $statement = "RhodeIsland";
    echo $statement." is ".${$statement} ."<br />";

    ?>

1 Comment

The OP was asking how to do it with variable variables, specifically. I assume he's trying to learn how it works :)
0

You should be using curly brackets instead of parentheses.

$statement = "RhodeIsland";
echo "$statement is ${$statement}<br>";

PHP documentation on the subject is here: http://www.php.net/manual/en/language.variables.variable.php

Comments

0

this works :)

    <?php
    $Texas = "large";
    $RhodeIsland = "small";

    $statement = "Texas";
    echo $statement." is ".$$statement."<br>";

    $statement = "RhodeIsland";
    echo $statement." is ".$$statement."<br>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.