Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting custom indexes in array

Tags:

arrays

php

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

);
like image 608
Lingo Avatar asked Dec 06 '22 01:12

Lingo


2 Answers

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.

like image 58
Jeff Rupert Avatar answered Dec 27 '22 23:12

Jeff Rupert


You can use foreach

foreach($myarray as $key=>$value)
{
    if(is_int($key))
    {
           //process the entry as you want
    }
}
like image 31
Maulik Vora Avatar answered Dec 27 '22 23:12

Maulik Vora