470,848 Members | 1,252 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,848 developers. It's quick & easy.

How to add element in php array dynamically?

HI

I want to add two element in a array. the first one is
the key and the second is the value.but I want to add it
dynamically. i want to do it like the following code:
$arr="";
for($i=0;$i<20;$i++) {

$arr[$i]=arr($i=>$i+1);

array_push($arr[$i]);

}

print_r($arr);

But of couse it don't work. Could anyone tell me how
to do it ?
Thx

Ricky
Jul 17 '05 #1
3 69384
ka*******@hotmail.com wrote:
I want to add two element in a array. the first one is
the key and the second is the value.but I want to add it
dynamically. i want to do it like the following code:
$arr="";
for($i=0;$i<20;$i++) {

$arr[$i]=arr($i=>$i+1);

array_push($arr[$i]);

}

print_r($arr);

But of couse it don't work. Could anyone tell me how
to do it ?


I'm no expert (see my own question!) but I think you would do this as:

for($i=0;$i<20;$i++) {

array_merge($arr, array($i => $i+1)}

}

In other words you merge your existing array with a new one consisting
of the new key=>value mapping that you want to add.

Or at least that's how I've done it before...

Andrew
Jul 17 '05 #2
<ka*******@hotmail.com> wrote in message
news:d8**************************@posting.google.c om...
HI

I want to add two element in a array. the first one is
the key and the second is the value.but I want to add it
dynamically. i want to do it like the following code:


$myArray = array( ); // initialize as empty array;

$myArray[] = 77; //add element 77
$myArray[] = 88; //add element 88

$myArray['newKey'] = 'valueForNewKey';

rush
--
http://www.templatetamer.com/

Jul 17 '05 #3
.oO(ka*******@hotmail.com)
I want to add two element in a array. the first one is
the key and the second is the value.but I want to add it
dynamically. i want to do it like the following code:
$arr="";
for($i=0;$i<20;$i++) {

$arr[$i]=arr($i=>$i+1);

array_push($arr[$i]);

}


Not really sure what mean. Could you explain or post an example of what
$arr should look like after the above loop?
I would simply interpret your code as

$arr = array();
for ($i = 0; $i < 20; $i++) {
$arr[] = array($i => $i+1);
}

but that's probably not what you wanna do.

Micha
Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by Zordiac | last post: by
33 posts views Thread by Zytan | last post: by
17 posts views Thread by Ron Peterson (012ED25E) | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.