Learn PHP in 17 Days

Easy, non-nonsense guides to learning php. 47 lessons in total - click to get your copy of these fantastic guides.

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:

array
(
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
{
...
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.

Are you a Developer, Designer or Copy Writer? Or Looking For One?

Click here to see 100s of jobs updated every day that you can complete to earn good money. Also find that programmer, designer or copy writer you have been looking for - advertise and get the best guy for your job - click here to find out more

Leave a Reply

Make $100,000/Month - Every Month!

It Works! We Make Our Customers Millionaires! Act now and get $600 bonus and a Free Money Making Website! - click to get started