Imran Khan
Imran Khan

Reputation: 2401

Concatenation php variables:

I have a problem in creating variable in a loop and accessing third variable value, i did try many way but now i don't know how to do that.... the code is..

$rand_1 =       random_username($_POST['txtuser_name']);
$rand_2 =       random_username($_POST['txtuser_name']);
$rand_3 =       random_username($_POST['txtuser_name']);

$username   =   "";

for($i=1; $i<=3; ++$i){
   $name   =    "rand_".$i;
   $username .= $name."<br />";
}

echo $username;

Any suggestion.....

Upvotes: 1

Views: 98

Answers (2)

alex
alex

Reputation: 490153

Try $$name, which is a variable variable.

Still, when you see var_1 etc, generally it means you should be using an array.

Then you could make your code...

$rand = array();

foreach(range(0, 2) as $index) {
    $rand[] = random_username($_POST['txtuser_name']);
}

$username = join('<br />', $rand) . '<br />'; 

Upvotes: 3

Gaurav
Gaurav

Reputation: 28755

use $username .= $$name."<br />"; instead of $username .= $name."<br />";

But better approach may be

$user=array();

for($i=1; $i<=3; ++$i){
   $user[] =  random_username($_POST['txtuser_name']);
}

echo implode("<br/>", $user)."<br />";

Upvotes: 1

Related Questions