Looping an array? Do it the foreach way

As an example if you have an array of users with an ID field as the key and the username as the value, such as:

{code type=php}
566 => ‘monkeybrains’,
891 => ‘bananaface ,
4459 => ‘treehugger’

You may want to perform an action on or with each of these array elements. If the array is assigned to the value $users you can loop through easily and logically as follows:

{code type=php}foreach ($users as $user_id => $user_name)
echo “$user_name has user_id $user_id”;
# will echo: monkeybrains has user_id 566

Doing it this way makes most sense to me and flows better in the code. In many situations I have seen programmers use the key of each array sequentially, so as to be able to loop the array in a for loop, such as:

{code type=php}for ($i=0; $i < sizeof($users); $i++) { ...{/code} For me this is cumbersome and does not read very well. It relys on your keys being ordered 0,1,2,3 ... etc. and to format them this way would probably take more coding and therefore resources.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *