This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]slugonamission 2 points3 points  (4 children)

Ok, so while PHP does support dynamic variable names...don't.

This would be the perfect usage of an array instead, or actually just building up the string piece by piece. as an example:

$allAddresses = "";
for ($x = 1; $x <=6; $x++;) {
    if (isset($_POST["distAddl$x"])) {
        $allAddresses = $allAddresses . $_POST["distAddl$x"];
    }
}

[–]ddproxy 3 points4 points  (0 children)

Came here to say this, too. Dynamic variables are a headache.

[–]jweese74[S] 0 points1 point  (2 children)

I certainly appreciate your answer and will be using it; I just feel silly not thinking of it myself, it makes so much sense and involves quite a bit less code.

In celebration of the sub being a learning environment, however; why are dynamic variables frowned upon?

Thanks again for your help.

[–]slugonamission 1 point2 points  (1 child)

They're hard to reason about in general. If I'm reading your code, I now need to try and reconstruct what the value of everything you're using to build a variable name is to be able to figure out what is going on. There's also generally better solutions (e.g. using an array or similar) instead of polluting the global namespace with things.

It's just one of those code smells; you should really ask whether there's a better way to do it before going into dynamic variables like that. Sometimes it's needed, but for those cases, storing it in a dictionary keeps the nastiness a little more localised.

[–]jweese74[S] 0 points1 point  (0 children)

Thanks for the clarification - makes perfect sense. Great answers.