views:

141

answers:

4

Hi guys. Might be an easy question for you guys. can't find it on google.

I am trying to concatenate two variables name;

$i=0;
 for ($i=0;$i<5;$i++){
   if($array[$i]>0){

   $test.$i=//do something
   }else{
  $test.$i=//do something
  }
}

//echo $test0 gives me nothing.
//echo $test1 gives me nothing.

I know I can't use $test.$i but don't know how to do this.Any helps? Thanks!

+1  A: 

This might work:

$varName = $test . $i;
$$varName = ...

Can i ask where for this is neccesary?

VDVLeon
I am trying to loop a two dimension arrays..its hard to explain here, but I need concatenation to get what I need. Thanks though. +1
Jerry
+8  A: 

try ${$test.$i} = value

EDIT: http://php.net/manual/en/language.variables.variable.php

Simon
good link! +1 to u.
Jerry
Accepted answer because of the link! :D
Jerry
The last two lines of the OP's code imply that if $i == 0, he's trying to access $test0. In this case, if $test is undefined, then $test will evaluate to the empty string and {$test.$i} will evaluate to "0".
Dazarath
I think, you have click below the score on the check to accept the answer ;)
Simon
I can't. there is a message pop up saying I have to wait for 3 min.
Jerry
ahhh..:D ... didn't know, sorry
Simon
+5  A: 

Try this:

 for ($i=0;$i<5;$i++){
    $the_test = $test.$i;
    if($array[$i]>0){
        $$the_test=//do something
    }
    else{
        $$the_test=//do something
    }
}
nc3b
thanks a lot! +1 to u.
Jerry
+2  A: 

I'm assuming that the variables are called $test0, $test1, ..., $test5. You can use the following:

${"test".$i}

Though, might I suggest that you make $test an array and use $i as the index instead? It's very odd to use $i as an index to loop through a list of variable names.

As an example, instead of:

$test0 = "hello";
$test1 = "world";

Use:

$test[0] = "hello";
$test[1] = "world";
Dazarath
I do like your suggestion. I already gave the accepted answer to Simon. +1 though :D
Jerry