Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Adding Key to array push

    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:
    PHP 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
    Code:
    Array
    (
        [gid] => 1163
        [capacity] => 8
        [speed] => 2
        [0] => Net Item
    )

  • #2
    New Coder
    Join Date
    Jan 2008
    Location
    Portugal
    Posts
    17
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Smile

    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)

    Code:
    <?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:

    Code:
    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.
    Last edited by weblive; 01-21-2008 at 05:05 PM. Reason: added the output

  • Users who have thanked weblive for this post:

    JohnDubya (01-21-2008)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •