variable name [SOLVED]

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
nayeemmz
Forum Commoner
Posts: 32
Joined: Fri Jun 29, 2007 7:19 pm

variable name [SOLVED]

Post by nayeemmz »

Hi,

I am having a problem which someone in this forum might be able to help me with.
I want to have a variable with a variable in its name

For e.g my if I have a loop

Code: Select all

for($num=0;$num<10;$num++)
I want to have a variable name like

inputdata$num which means 10 variables should be formed after the loop terminates
inputdata1, inputdata2......inputdata10.


I am unable to do this.

Can someone help please?


Thanks
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Check out variable variables in the php manual.

Code: Select all

$num = 4;
${'inputdata' . $num} = 'gobblygooooo';

echo $inputdata4;  // echo's gobblygooooo
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

You can also use an array

Code: Select all

<?php
$inputdata = array();
$inputdata[] = 'xyz';
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I've found using a keyed array (a hash, really) is way less prone to errors. Plus you get all the benefits of the array functions for checking existence etc...
elinews
Forum Commoner
Posts: 38
Joined: Tue Aug 14, 2007 7:18 pm

Post by elinews »

I just had this same problem. It's a really quick fix. I think this is what I did:

Code: Select all

$inputdata[$num]="whatever";
nayeemmz
Forum Commoner
Posts: 32
Joined: Fri Jun 29, 2007 7:19 pm

Post by nayeemmz »

Thankyou all.

Your solutions work.

I really appreciate it.
Post Reply