1

I know this is not the proper way to do this, however I am trying to put a quick fix on a form that was done by another developer. Basically I want to add an incremental number to a variable inside a while statement:

$count = 1;
while ($r = mysql_fetch_array($query)) {
    $variable . $count = $r['somefield'];
        $count++
}

So that makes the variables:

$variable1 $variable2 $variable3 ....etc

3
  • 1
    Basically any time you need variable variables, you're doing something wrong. Use arrays. That's what they're for. Commented Jun 11, 2012 at 21:16
  • Thanks Mike. As I stated.. I know it is the completely wrong way to do it. I just needed a quick fix for a form that another developer had done with some 400 fields and NO ARRAYS!! For this case, variable variables saved me some 4 or 5 hours from having to rewrite the entire structure of the form. Commented Jun 11, 2012 at 21:20
  • Ah, sorry. I must have read your post too fast. Commented Jun 11, 2012 at 21:33

2 Answers 2

4
$varname = 'variable' . $count;
$$varname = $r['somefield'];

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

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

2 Comments

This solved my dilemma! Thank You! I hate it when I open up a script that was written years ago by an inexperienced developer.
@Prince, I can really feel your pain. :-)
1

You'd be better off with an array...

$variable[] = $r['somefield'];

You can use variable variables, however it is probably not a good idea, especially for a trivial case like this one.

Comments

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.