PHP代码中如何让echo $test输出6而非$j7?
Got it, let's figure out how to fix this for you!
First, let's understand why your current code outputs $j7 instead of 6. In PHP, single quotes (') treat everything inside them as literal text—so '$j' doesn't get parsed as the variable $j, it's just the string $j. When you concatenate that with $b (which is 7), you end up with the string $j7, not the value of the actual variable $j7.
Now, here are a few solid ways to get the output 6:
1. Use Double Quotes with Curly Braces
PHP parses variables inside double quotes, and curly braces let you clearly define the full variable name when it's followed by other characters. This is clean and readable:
<?php $j7 = 6; $b = 7; $test = "${j$b}"; // This resolves to the variable $j7 echo $test; ?>
The ${j$b} tells PHP to combine the string j with the value of $b (7) to make the variable name j7, then grab its value (6).
2. Use Variable Variables
This is another straightforward approach. First build the variable name as a string, then use two dollar signs to access its value:
<?php $j7 = 6; $b = 7; $varName = 'j' . $b; // Creates the string 'j7' $test = $$varName; // $$varName is the same as $j7 echo $test; ?>
This is great if you need to dynamically build variable names often—it's explicit and easy to follow.
3. Avoid eval() (Unless Absolutely Necessary)
While this works, eval() is risky if you're dealing with any user-provided input, since it executes arbitrary code. But for completeness, here's how it would look:
<?php $j7 = 6; $b = 7; eval("\$test = \$j$b;"); echo $test; ?>
The backslashes escape the first $ so PHP correctly parses $j$b as $j7.
My go-to recommendations are Method 1 or 2—they're safe, readable, and fit most use cases. Either one will make your echo $test output 6 like you want.
内容的提问来源于stack exchange,提问作者Muhammad Afdhal Bin Hassan

