Creating dynamic variables, change variable names

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
black_hat
Forum Newbie
Posts: 9
Joined: Thu Sep 10, 2009 4:48 am
Location: Los Angeles

Creating dynamic variables, change variable names

Post by black_hat »

I'm pulling four strings from a database, I want to create PHP variables named one for each of these strings.

for each string s do
create variable ($s)


resulting in

<?php>

....
$X
$X
$Y
$Z
...

</?>
Is this even possible or would I need to go through a file manipulator script?
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Creating dynamic variables, change variable names

Post by Mark Baker »

Code: Select all

 
foreach($string as $s) {
   $$s = null;
}
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Creating dynamic variables, change variable names

Post by requinix »

There are very, very few reasons why doing that would be a good idea.

What is this code supposed to do?
User avatar
black_hat
Forum Newbie
Posts: 9
Joined: Thu Sep 10, 2009 4:48 am
Location: Los Angeles

Re: Creating dynamic variables, change variable names

Post by black_hat »

I'm pulling a big query from the DB, ordering by valueName, for this example let's say the valueName are human names (john, Jack, etc.).

So the query comes back as

John __*__1
John __*__2
John __*__44
Jack __*__3
Jack __*__21
Jill __*__533
Jill __*__213
Jill __*__11
Jil __*__12

I want to split this large return into lists identified by their valueName. Such as,

$John = array(1,2,44);
$Jack = array(3,21);
$Jill = array ("533,213,11,12);

To which I will feed into a graphing function to draw each as its own line, and creating a graph legend based on the array name given. I'd rather split it like this than have to modify and add logic to the graphing function.
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Creating dynamic variables, change variable names

Post by peterjwest »

As tasairis suggested, this is a bad way of programming. Variable variables are pretty dumb and unneccessary.

Quite simply you can make an array like this:

Code: Select all

$people = array( 
   'John' => array(1,2,44),
   'Jack' = array(3,21),
   'Jill' = array (533,213,11,12)
)
You can pass this array into the grapher, or pass each value/key.
e.g.

Code: Select all

graph($people);
//or..
foreach($people as $name => $person) {
   graph($people[$name],$name); 
}
User avatar
black_hat
Forum Newbie
Posts: 9
Joined: Thu Sep 10, 2009 4:48 am
Location: Los Angeles

Re: Creating dynamic variables, change variable names

Post by black_hat »

Perfect, exactly what I need. Mind fudge, I completely forgot about that
Post Reply