Skip to content
Advertisement

Call an existing php variable by concatenating two strings

I have these seven php variables:

$dataA = 1;
$targetA = 2;
$dataB = 3;
$targetB = 4;
$dataC = 5;
$targetC = 6;
results = array('A','B','C');

I would like to loop through the results array and pass the corresponding variables to a function.

foreach($results as $value) {
    $data = '$data'.$value;
    $target = '$target'.$value;
    buildOutput('$data'.$value,'$target'.$value); 
}

// example, first time thru, wish to pass $dataA variable and $targetA variable

function buildOutput($data,$target) {
    echo "data=$data,target=$target<br>"; // echo's strings "$dataA" and "$targetA"
}

I cannot figure out how to declare the variables. Or if this is even possible.

I have more than just $data and $target variables, but I simplified down to two for the question.

Advertisement

Answer

I would not recommend using it, but try this:

$dataA = 1;
$targetA = 2;
$dataB = 3;
$targetB = 4;
$dataC = 5;
$targetC = 6;

$results = array('A','B','C');

foreach($results as $value) {
  buildOutput(${'data'.$value}, ${'target'.$value}); 
}

function buildOutput($data, $target) {
  echo "data=$data,target=$target<br>";
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement