Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php merging or concatenation strings when assigning a variable

Tags:

php

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?

like image 783
Ghostff Avatar asked Jun 02 '26 17:06

Ghostff


2 Answers

$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;
    }
}
like image 80
DirtyBit Avatar answered Jun 05 '26 05:06

DirtyBit


Assign it like so.

${$m.$i} = 20;
like image 23
monkee Avatar answered Jun 05 '26 06:06

monkee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!