3

PHP NOOB, i have been working on this code all day, but cant find any good way to fix it.

here is my code:

$priv = explode(',', '0,1,1');
$m = 'me';
for($i = 0; $i <= 2; $i++)
{
    if($priv[$i] == '0')
    {
        $m.$i = 20;
    }
    else
    {
        $m.$i = 10;
    }
}

Am trying to join $m.$i together and set it to 20 or 10, but i end up having me20 or me10 instead of me1 = 20 or me1 = 10 when i echo $m.$i which is legit, is there anyways to make this work?

2
  • 1
    when i echo $k.$m which is legit Where is $k? Commented Oct 4, 2015 at 8:35
  • Ahh, its okay and now I think you meant me0 = 20 ? Commented Oct 4, 2015 at 8:38

3 Answers 3

5

$m.$i = 20;

This will assign $i = 20 and then concatenate it with $m and hence you will see me20.

What you need is $m . $i .= 20; instead. which will concatenate them altogether.

Fixed:

<?php

    $priv = explode(',', '0,1,1');
    $m = 'me';
    for($i = 0; $i <= 2; $i++)
    {
        if($priv[$i] == '0')
        {
          echo  $m . $i .= 20;
        }
        else
        {
         echo   $m.$i .= 10;
        }
    }
    ?>

EDIT:

The above answer was a total misunderstanding, I realised you intended to create the variables:

for($i = 0; $i <= 2; $i++)
{
    if($priv[$i] == '0')
    {
        ${$m.$i} = 20;
        echo $me0;
   }
    else
    {
        ${$m.$i} = 10;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i want $m0 = 20 or $m0 = 10
@ChrysUgwu Ahh Crap.. I just realized. fixing it in a minute.
2

Assign it like so.

${$m.$i} = 20;

Comments

1

You are trying to dynamically create variables, so you have to do something like this:

$priv = explode(',', '0,1,1');
$m = 'me';
for($i = 0; $i <= 2; $i++)
{
    if($priv[$i] == '0')
    {
        ${$m.$i} = 20;
    }
    else
    {
        ${$m.$i} = 10;
    }
}

then try to priny $me0, $me1

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.