0

I have the following code that works:

$apple_color = "red";
$pear_color = "green";
$banana_color = "yellow";
$grape_color = "purple";

foreach(array("apple","pear","banana","grape") as $idx=>$fname) {
    $var = "${fname}_color";
    echo "$var = ${$var}<br>".PHP_EOL;
}

However, I cannot figure out how to shorten the code by eliminating the $var variable to something like this:

foreach(array("apple","pear","banana","grape") as $idx=>$fname) {
    echo "${fname}_color = ${${fname}_color}<br>".PHP_EOL;
}

The "${${fname}_color" returns an PHP error that says "syntax error, unexpected '_color' (T_STRING)"

PHP Fiddle: http://phpfiddle.org/lite/code/wrfp-yqkx

3 Answers 3

1

How about this? Use ${'string'} construction

foreach(["apple","pear","banana","grape"] as $fname) {
    echo "{$fname}_color = ".${$fname.'_color'}."<br>".PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of having a separate variable for each color, store the colors in an array indexed by the fruit name. This way you can avoid the mess of using variable variables.

$colors = [
    'apple' => 'red',
    'pear' => 'green',
    'banana' => 'yellow',
    'grape' => 'purple'
];

foreach (["apple","pear","banana","grape"] as $fname) {
    echo "{$fname}_color = $colors[$fname]<br>".PHP_EOL;
}

1 Comment

Your idea works, however, in my situation, I have no control over the initial variable names that is passed into my code.
0

Use string formatting to simplify your life:

echo sprintf('$%s_color = %s<br>' . PHP_EOL, $fname, ${$fname . '_color'});

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.