0

I have a variable called $repeater, which will either be low, moderate or high.

I also have variables called...

$low_protein_feed
$moderate_protein_feed
$high_protein_feed

I want to call one of these variables depending on what the value of $repeater is.

I got as far as this...

echo "${$repeater}_protein_feed";

...which outputs moderate_protein_feed, for example. But it echoes as text, when I want it to be echoing the value of $moderate_protein_feed variable.

I feel like I'm not far off. Thanks for any input

bboybeatle
  • 549
  • 1
  • 8
  • 28

4 Answers4

2

Though i advise against this sort of programming, Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: you will want to use $$ to set the variable to a variable name. http://php.net/manual/en/language.variables.variable.php

Test scenario:

$myvariable = "hello";
$$myvariable = "hello2";

is the same as

$hello = "hello2";

for your case:

$low_protein_feed = "test1";
$moderate_protein_feed = "test2";
$high_protein_feed = "test3";

$repeater = "low";
echo ${$repeater . "_protein_feed"};

returns test1

check out a related security article http://rgaucher.info/php-variable-variables-oh-my.html

Plixxer
  • 466
  • 4
  • 15
2

let me purpose an alternative approach, one that most developers agree is better than using variable variables:

//array for the protein_feed's
    $protein_feed=array('low'=>'1','moderate'=>'2','high'=>'3'); 
//then to select one based on the value of $repeater
    echo $protein_feed[$repeater];
0

I think you are looking to do something like this:

<?php

// Example - though you should use objects, key -> values, 
// arrays instead in my opinion.

$low_protein_feed = "Low protein";
$moderate_protein_feed = "Lots of protein";
$high_protein_feed = "high grade protein";

$types = array("low", "moderate", "high");

foreach($types as $type) {

    echo ${$type . '_protein_feed'} . " \n";

}

Output:

$ php testme.php 
Low protein 
Lots of protein 
high grade protein 

However, you should really use something like this:

$types = array("low", "moderate", "high");
$proteins=array('low'=>'1','moderate'=>'2','high'=>'3'); 

foreach($types as $type) {
    echo $proteins[$type];
}

More advanced design, you can use objects and declare a type of said object and use a standard type for projects.

Further reading on dynamic variable names here and the differences between PHP5/7 :

Using braces with dynamic variable names in PHP

http://www.dummies.com/programming/php/how-to-use-php-variable-variables/

Mike Q
  • 6,716
  • 5
  • 55
  • 62
0

Another way: $GLOBALS[$side . $zi_char]

Yakun Hu
  • 1
  • 3