tags:

views:

77

answers:

4

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 = 
   );

);
+9  A: 
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.

Jeff Rupert
+1 but it is better to use `is_int` or `ctype_digit` :)
Sarfraz
Note that a string containing a numeric value will also be processed now, if that is a problem, use is_int (perhaps with is_float if you want non-ints as well) instead.
Jasper
I've never heard of `ctype_digit`. Time to go do some research!
Jeff Rupert
+4  A: 

You can use foreach

foreach($myarray as $key=>$value)
{
    if(is_int($key))
    {
           //process the entry as you want
    }
}
Maulik Vora
+3  A: 

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
}
ircmaxell
Interesting approach. When did PHP get `Iterator` classes? (I don't do much OOP with PHP, too much of our codebase at my company is pre-built, and I usually build other things in my free time.)
Jeff Rupert
Since PHP 5.1... See the [SPL Iterators](http://us.php.net/manual/en/spl.iterators.php) and the [Iterator Interface](http://us.php.net/manual/en/class.iterator.php)
ircmaxell
A: 

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]);
}
Marc B
that's (quite a bit) slower, uses more memory and is less readable - I don't see any advantage to this method, actually.
Jasper
Just another alternative. Might be more usesable if you're on an older PHP and/or don't have SPL available.
Marc B