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 3 of 3
  1. #1
    New Coder
    Join Date
    Oct 2012
    Posts
    25
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Adding elements to a list within an array

    I'm somewhat familiar with python, and so am still getting by barrings with PHP.

    I have an array with named keys. Each key's value is a list of items. How do I add items to the value?

    Array
    "Cars" => "1, 12, 22";
    "Trucks" => "3, 5, 18, 9";
    "Vans" => "5";

    Say I want to add "17" to "Cars", how would I do that?

    Thanks!

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    PHP Code:
    $a = array(
        
    'Cars' => array(11222),
        
    'Trucks' => array(35189),
        
    'Vans' => array(5)
    );

    // Add 17 to cars:
    $a['Cars'][] = 17// treats it similar to push.
    array_unshift($a['Cars'], 17);
    array_push($a['Cars'], 17); 
    Simple as that.

  • Users who have thanked Fou-Lu for this post:

    comport9 (11-20-2012)

  • #3
    New Coder
    Join Date
    Oct 2012
    Posts
    25
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks huge man!


  •  

    Posting Permissions

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