0

Following my unsolved question, I'm trying to figure how to use foreach

How can I make this kind of code:

$m1="mbob";
$m2="mdan";
$m3="mbill";

$a = array('bob', 'dan', 'bill');

$i = 1; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    echo $m[$i];
    $i++;
}

To output this result:

$a[1] => bob.
mbob
$a[2] => dan.
mdan
$a[3] => bill.
mbill

I'm getting the error:

Undefined variable: m

But I'm trying to output the m1,m2,m3 variables, not just m.

4
  • 1
    it's not a repost, it's a related question. Commented Jan 20, 2016 at 23:23
  • Are you unable to make the $m values into an array? Because what you are asking for is pretty bad practice, arguably. Commented Jan 20, 2016 at 23:25
  • @Fred-ii- - No... that's your assumption, under the guise of logic. Commented Jan 20, 2016 at 23:27
  • @HC_ I don't want to make it into an array, if you'll take a look at my previous question you'll see that an array wouldn't fit, as I'll have to create dozens of arrays and it will be a mess to change values when needed. Commented Jan 20, 2016 at 23:29

3 Answers 3

1

That's something I've never done but you may try and give it a shot:

echo $('m' . $i);

That's similar to function invocations where you construct the function name dynamically through a string, but I don't know if it works with local variables as well.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is code that works, but I would not recommend it. I would recommend just storing your $m values in an array.

<?php
    $m1="mbob";
    $m2="mdan";
    $m3="mbill";

    $array = array('bob', 'dan', 'bill');
    $i = 1;
    foreach ($array as $value) {
        echo "\$a[$i] => $value.\n";
        echo '<br>';
        echo ${"m".$i};
        echo '<br>';
        $i++;
    }
?>

Comments

0

In your code, $m is not an array. There is a way to create variable variable names which appears to be what you are trying to do, but simpler is to create $m as an array:

$m =array("mbob","mdan","mbill");

$a = array('bob', 'dan', 'bill');

$i = 1; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    echo $m[$i];
    $i++;
}

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.