SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Nov 2004
    Location
    New Jersey
    Posts
    317
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using compact() with the elements of an array?

    Is it possible to apply compact() to the elements of an array? For instance, instead of
    Code:
    $name = 'John';
    $city = 'Denver';
    $state = 'Colorado';
    print_r(compact('name', 'city', 'state'));
    Something like
    Code:
    $arr['name'] = 'John';
    $arr['city'] = 'Denver';
    $arr['state'] = 'Colorado';
    print_r(compact(...on each key of $arr...));
    I was thinking of iterating over $arr with a foreach() loop and compact()ing each element individually, but I don't know how to pass the element keys as varnames that make sense to compact().

  2. #2
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,398
    Mentioned
    65 Post(s)
    Tagged
    1 Thread(s)
    Your example makes no sense (to me) as the result of compacting based on your description would be... the original array!
    Salathe
    Software Developer and PHP Manual Author.

  3. #3
    SitePoint Addict
    Join Date
    Nov 2004
    Location
    New Jersey
    Posts
    317
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes this particular case would be rather pointless Just something I was curious about.

    I suppose what I'm really asking is if there's a way to pass array elements as varnames.

  4. #4
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    75
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not sure if I understand, but implode and explode seem to fit that. Or maybe:

    Code:
    $new_array = array($$name => $name, ....

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    PHP Code:
    $arr['name'] = 'John';
    $arr['city'] = 'Denver';
    $arr['state'] = 'Colorado';

    extract($arr);
    call_user_func_array('compact',array_keys($arr)); 
    ?


Bookmarks

Posting Permissions

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