1

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

2 Answers 2

3

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 />'; 
Sign up to request clarification or add additional context in comments.

1 Comment

@Ibu Just an easier way to loop through numbers than with a normal for loop.
1

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

3 Comments

its all work with $$name,, and the second method is also good.
Your better approach won't produce the same output as the OP's code.
@lex, hey man you both are right but in loop i also want to check in db. so thats why it is not perfect to implode or join all username, but simply check in loop if not exist in d.b then join with username otherwise go next....so $query1 = "select count(*) from member_details where username ='".$$name."'"; $nameCount = dbQuery($query1, 'count'); if($nameCount==0){ $username .= $$name."<br />"; }

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.