Looping an array? Do it the foreach way

by Carey on November 20, 2010

Post image for Looping an array? Do it the foreach way
  • Share
  • CevherShare
  • Share

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:

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:

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:

for ($i=0; $i < sizeof($users); $i++)

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.

Leave a Comment

Previous post:

Next post: