6

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!

4 Answers 4

28

try ${$test.$i} = value

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

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

5 Comments

Accepted answer because of the link! :D
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".
I think, you have click below the score on the check to accept the answer ;)
I can't. there is a message pop up saying I have to wait for 3 min.
ahhh..:D ... didn't know, sorry
8

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";

1 Comment

I do like your suggestion. I already gave the accepted answer to Simon. +1 though :D
6

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
    }
}

Comments

1

This might work:

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

Can i ask where for this is neccesary?

1 Comment

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

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.