PHP Concatenation Variable

It may be easy for you to ask questions. can't find it on google.

I am trying to bind the name of two variables;

$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 that I can not use $ test. $ i, but don’t know how to do it. Thanks!

+6
variables php concatenation
source share
4 answers
+27
source share

I assume the variables are called $ test0, $ test1, ..., $ test5. You can use the following:

 ${"test".$i} 

Although, can I suggest you make $ test an array and use $ i instead of the index instead? It is very strange to use $ i as an index to scroll through the list of variable names.

As an example, instead of <

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

Using:

 $test[0] = "hello"; $test[1] = "world"; 
+7
source share

Try the following:

  for ($i=0;$i<5;$i++){ $the_test = $test.$i; if($array[$i]>0){ $$the_test=//do something } else{ $$the_test=//do something } } 
+6
source share

This might work:

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

May I ask where it is needed?

+1
source share

All Articles