...

View Full Version : Adding Key to array push



ptmuldoon
01-21-2008, 05:45 PM
I'm trying to add another value to an existing array using array_push. But when I do so, the key is being assigned as '0', when I would like to give it a name.

Is array push the best method to use, or is there a another/simpler way?

Here's the code:


while ($row = mysql_fetch_assoc($rs_result)) {

$add_item = 'Net Item';
array_push($row,$add_item);

echo '<pre>';
print_r($row);
echo '</pre>';
?>

And the output is


Array
(
[gid] => 1163
[capacity] => 8
[speed] => 2
[0] => Net Item
)

weblive
01-21-2008, 06:03 PM
hi,

the best way I can remember to do this, unless you want it to be dynamic in some way (I'm sorry but you didn't explain the use for that), is to "manually" insert that item in the array, otherwise array_push() is just going to assign the next numeric index (in the case you've shown, 0)


<?php
while ($row = mysql_fetch_assoc($rs_result)) {

$add_item = 'Net Item';
$row['name_you_want'] = $add_item;

echo '<pre>';
print_r($row);
echo '</pre>';
?>

The output should be:



Array
(
[gid] => 1163
[capacity] => 8
[speed] => 2
[name_you_want] => Net Item
)


Note that this won't insert anything in the db, if that's what you want...

Anyway, if it doesn't do what you want, explain better your intention.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum