0

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.

2
  • Please use arrays to store values: array('A' => ['data' => 1, 'target' => 2]); // etc Commented Nov 30, 2021 at 7:03
  • I didn't wish to make the example complicated, but the $data's are associative arrays. The $target's are not. But I will re-think this. Commented Nov 30, 2021 at 7:46

1 Answer 1

1

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>";
}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked. Thank you. But why "would not recommend"? I'm only using this on my localhost.
im not recommend it, because it could break your code with wrong data/values, or cause some unexpected behavior. I would suggest to use Arrays, if possible. If only using for yourself, its ok, i guess.

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.