Lingo
Lingo

Reputation: 1875

Selecting custom indexes in array

I have an nested array that's a mix of words and numbers. It looks like this conceptually. I need to process only numbered indexes such as 15 and 28. I guess this means that I can't use a foreach loop (or is there a way I could). How would you do this?

myarray = (

   someindex = (
     field1 = 
     field2 = 
   );

   15 = (
     field1 = 
     field2 = 
   );

   28 = (
     field1 = 
     field2 = 
   );

   anothertext = (
     field1 = 
     field2 = 
   );

);

Upvotes: 4

Views: 567

Answers (4)

Marc B
Marc B

Reputation: 360662

Another version. Grep the source array for any purely numeric keys, then loop over that result array and do the processing.

$keys = preg_grep('/^\d+$/', array_keys($myarray)) {
foreach($keys as $key) {
    doSomething($myarray[$key]);
}

Upvotes: 0

ircmaxell
ircmaxell

Reputation: 165201

You could use a FilterIterator with foreach:

class IntKeyFilterIterator extends FilterIterator {
    public function accept() {
        return is_int(parent::key());
    }
}

$it = new IntKeyFilterIterator(new ArrayIterator($array));
foreach ($it as $value) {
    // Will only have those with int keys
}

Upvotes: 3

Jeff Rupert
Jeff Rupert

Reputation: 4840

foreach($myarr as $key => $item)
{
    if(is_int($key))
    {
        // Do processing here
    }
}

Yes, that will loop through every item in the array, so if you wanted to process the other items separately, you could just add in an else block.


Edit: Changed is_numeric to is_int. See comments for explanation.

Upvotes: 9

Maulik Vora
Maulik Vora

Reputation: 2584

You can use foreach

foreach($myarray as $key=>$value)
{
    if(is_int($key))
    {
           //process the entry as you want
    }
}

Upvotes: 4

Related Questions