SitePoint Sponsor

User Tag List

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

    Iterating numeric keys only in arrays with mixed numeric, associative keys?

    Is there a good way to iterate over the numeric keys only in an array with mixed numeric and associative keys, other than brute force where you use do a foreach() and then use something like is_numeric() the individual keys?

    For instance I have an array like
    PHP Code:
    $array = array('0'=>'zero''1'=>'one''2'=>'two''3'='three''fruit'=>'orange''color'=>'green''plant'=>'grass'); 
    And I want to iterate over the 0, 1, 2, and 3 elements only.

  2. #2
    SitePoint Member
    Join Date
    May 2009
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I just tried the following and the result is an array with only the numerically-indexed entries:

    $array = array('0'=>'zero', '1'=>'one', '2'=>'two', '4'=>'three', 'fruit'=>'orange', 'color'=>'green', 'plant'=>'grass');
    $array2 = array_values($array);
    $array3 = array_intersect_key($array, $array2);

    [09-May-2009 20:36:00] Array1
    (
    [0] => zero
    [1] => one
    [2] => two
    [4] => three
    [fruit] => orange
    [color] => green
    [plant] => grass
    )

    [09-May-2009 20:36:00] Array2
    (
    [0] => zero
    [1] => one
    [2] => two
    [3] => three
    [4] => orange
    [5] => green
    [6] => grass
    )

    [09-May-2009 20:36:00] Array3
    (
    [0] => zero
    [1] => one
    [2] => two
    [4] => three
    )

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If numeric keys are sequential and no gaps exist between integers, you could just use a standard for loop. But otherwise, here's an alternative which comes to mind

    PHP Code:
    $new array_combine(array_filter(array_keys($array), 'is_int'), $array); 
    Personally I think I would just use a foreach and check the key with is_int() inside the loop. It's painfully obvious and clear what you're doing in that case, unlike the snippit I just posted. It's probably also faster.


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
  •