Forum Moderators: coopster

Message Too Old, No Replies

Creating a variable with its name set to the contents of another

         

bleak26

2:43 pm on Feb 13, 2006 (gmt 0)

10+ Year Member



Can anyone tell me how to create a variable with its name set to the contents of another variable

for ($i=0;$i<10;$i++){
//new variable should have the name of the contents of $i
}

so i would end up with 10 variables e.g. $1,$2,$3,$4,$5,$6,$7,$8,$9,$10

is there a method available that does not use eval()

thanks guys.

Robber

2:59 pm on Feb 13, 2006 (gmt 0)

10+ Year Member



In php your variables should start with letters or underscores, so you can't create variables like $1.

However, it is possible to achieve what you are after in terms of creating variable names based on the contents of another variable.

eg:

$a = "xyz";
$$a = "hello";
print $xyz; // Outputs hello

FiSH42

3:25 pm on Feb 13, 2006 (gmt 0)

10+ Year Member



Probably the best (and cleanest) method of operating with loops and numbers would be to use an array,

for ($i=0;$i<10;$i++){
//new variable should have the name of the contents of $i
$myArray[$i] = 'contents';
}

So you can now loop through, or reference contents by value, in the same way as you would with numbered variable names.

F.

bleak26

4:28 pm on Feb 13, 2006 (gmt 0)

10+ Year Member



my original intention was to create many event objects and place them in events array, i figured i could not give them all the same name. so i thought i should now give the names of the objects the value of a loop iteration $1 (with hind sight and the help of you guys, with an underscore aswell e.g. $_1).

function instantiate_event($db_row_event,$posterdetails,$name){

$$name = new event(
$db_row_event['posteddate'],
$db_row_event['eventdate'],
$db_row_event['eventtitle'],
$db_row_event['eventdescription'],
$db_row_event['disabled'],
$db_row_event['admindisabled'],
$db_row_event['postedbyaccid'],
$db_row_event['memidofmemorial'],
$db_row_event['uniqueeventid'],
$posterdetails['firstname']);
return $$name;
}

//where it instantiates an event and places it in the events array
for ($i=0;$i<10;$i++){
$name = $i
events['$i'] = $this->instantiate_event($db_row_event,$posterdetails,$name);
}
is there a better way to do this?

is there a way to store an object in an array. where the array index is used to reference the object stored in it.