Page 1 of 1

Simplify this code?

Posted: Sun Feb 17, 2008 7:08 pm
by alex.barylski
Currently I have somehting like:

Code: Select all

foreach($modules as $module => $module_ids){
    foreach($module_ids as $module_id => $value){
        $module_ids_count++;
    }
}
Because all I am doing is basically counting the number of elements in each sub-array I would much rather simplify the code and *not* use any foreach if possible.

Can anyone think of a one liner to accomplish this, maybe using a combination of array_map or something?

Re: Simplify this code?

Posted: Sun Feb 17, 2008 7:11 pm
by Benjamin

Re: Simplify this code?

Posted: Sun Feb 17, 2008 7:38 pm
by alex.barylski
Unfortunately, I need the number of elements in the sub-array's not the values...unless I'm missing something about that function??

I was leaning towards maybe an array_map and a lambda function...but nothing really strikes me as easier than using two foreach loops...

Re: Simplify this code?

Posted: Sun Feb 17, 2008 7:40 pm
by Benjamin
I dunno, the code you have works, I wouldn't spend too much time on it. If it was me I'd try to count them at the source, where the data is entered into the array.

Re: Simplify this code?

Posted: Sun Feb 17, 2008 9:04 pm
by Luke
one line :)

Code: Select all

foreach($modules as $module) $module_ids_count += count($module);