Simplify this code?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Simplify this code?

Post 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?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Simplify this code?

Post by Benjamin »

alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Simplify this code?

Post 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...
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Simplify this code?

Post 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.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: Simplify this code?

Post by Luke »

one line :)

Code: Select all

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