Selecting custom indexes in an array

I have a nested array containing a combination of words and numbers. It looks conceptual . I need to handle only numbered indexes like 15 and 28 . I suppose this means that I cannot use the foreach (or is there a way I could). How do you do this?

 myarray = ( someindex = ( field1 = field2 = ); 15 = ( field1 = field2 = ); 28 = ( field1 = field2 = ); anothertext = ( field1 = field2 = ); ); 
+4
source share
4 answers
 foreach($myarr as $key => $item) { if(is_int($key)) { // Do processing here } } 

Yes, this will go through each element of the array, so if you want to process the other elements separately, you can simply add an else to the block.


Edit: Changed is_numeric to is_int . See Comments for an explanation.

+9
source

You can use foreach

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

You can use 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 } 
+3
source

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

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

All Articles