Reputation: 14250
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!
Upvotes: 6
Views: 25420
Reputation:
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";
Upvotes: 8
Reputation: 16220
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
}
}
Upvotes: 6
Reputation: 9365
try ${$test.$i} = value
EDIT: http://php.net/manual/en/language.variables.variable.php
Upvotes: 28
Reputation: 1394
This might work:
$varName = $test . $i;
$$varName = ...
Can i ask where for this is neccesary?
Upvotes: 1