Forum Moderators: coopster

Message Too Old, No Replies

dynamic array name

         

smagdy

8:11 pm on Feb 16, 2005 (gmt 0)

10+ Year Member



hi,

How to create PHP array with dynamic name?

thanks

jatar_k

8:47 pm on Feb 16, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well it is a very vague question but I have always used variable variables [php.net]

$a = 'apple';
$num = '5';

${$a . $num} = array('one','two','three');

echo '<pre>';
print_r($apple5);
echo '<pre>';

make any sense at all?

smagdy

9:01 pm on Feb 16, 2005 (gmt 0)

10+ Year Member



yeah makes sense but i wouldnt figure out this:

${$a . $num} = array(...)

but thanks ill try it.

jatar_k

9:13 pm on Feb 16, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



the thing that makes it hard is I don't know what you are creating the array name dynamically from.

I use it for all sorts of things.

Mostly when I don't know how many of something there will be so I use a counter to create the vars. ending up with var1, var2, var3, etc. I can then loop through, or just use, them later no matter how many there end up being.

smagdy

10:15 pm on Feb 16, 2005 (gmt 0)

10+ Year Member



Sorry am still confused.

how to insert some value in the array after the initializing and also how to echo whats inside the array?

smagdy

10:28 pm on Feb 16, 2005 (gmt 0)

10+ Year Member



Please look at this:

$getDose=0;

$a = 'comp';
$$a=$getDose; //This create variable $comp=0.

$a.${$a} = array(); //This create array named comp0
$a.${$a}[0]="sherif"; //This put "sherif" in index[0]

hope what i am saying is right... so the problem now is i cant display what is at index[0].

i tried:
echo"$a.${$a}[0]";

it gave:
comp.Array[0]

so what should i do?

thanks in advance

jatar_k

10:40 pm on Feb 16, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



try this

$getDose=0;
$a = 'comp';

${$a . $getDose}

this is constructing the variable name, it reads something like this

the variable who's name is the value of the variable a concatenated with the value of the variable getDose.

so..

${$a . $getDose} = array();
${$a . $getDose}[0] = 'sherif';

echo ${$a . $getDose}[0];

any better?

smagdy

10:52 pm on Feb 16, 2005 (gmt 0)

10+ Year Member



Thanks thanks... it worked.