DevChunks

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}
array
(
566 => ‘monkeybrains’,
891 => ‘bananaface ,
4459 => ‘treehugger’
){/code}

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
}{/code}

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.

Share:

Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,

Iteration

If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the