Home > Articles

Like this article? We recommend

Looping

If you were an assembly line worker, your job might be to repeat a set of steps over and over again throughout the day. If you installed the rearview mirror on the windshield, you would perform the same steps for installing each one. You would perform these steps until your shift ended and then you'd go home for the day. This process might contain the following steps:

    Step 1 Car arrives to your station

    Step 2 Take rearview mirror from its packing

    Step 3 Measure windshield to determine middle of width

    Step 4 Affix rearview mirror with adhesive

    Step 5 Test that the mirror is working properly

You would repeat each of these steps for every car that comes to your station until your shift was over.

The <CFLOOP> Tag

Looping in the programming world is similar because it allows you to repeat a set of instructions or display output over and over until one or more conditions are met. The <CFLOOP> tag allows you to create programming loops in CFML. This tag has an opening and closing tag, with the instructions you want to perform multiple times enclosed within the tags:

<CFLOOP ..>
HTML or CFML code to loop over ...
</CFLOOP>

<CFLOOP> supports five different types of loops:

  • Looping over a list

  • Index loops

  • Condition loops

  • Looping over a query

  • Looping over a structure

The type of loop is determined by the attributes of the <CFLOOP> tag. You won't understand the last two types of loops (query and structure) until you learn about those concepts.

NOTE

You will be learning about structure loops in Hour 18, "Using Advanced Variable Types."

Looping over a List

As an example of a loop list, you can take a list of colors and display them in table cells:

<TABLE BORDER="1">
 <TR>
 <CFLOOP INDEX="MyColor"
   LIST="red,blue,silver"
   DELIMITERS=",">
  <CFOUTPUT>
  <TD BGCOLOR="#MyColor#">
   <B>#MyColor#</B>
  </TD>
  </CFOUTPUT>
 </CFLOOP>
 </TR>
</TABLE>

Figure 6.5 depicts the output of this code.

Figure 6.5 This output is generated by looping through a list of colors and printing them into table cells.

Wrapping Code

Notice my <CFLOOP> tag and its attributes are each on separate lines and nicely aligned. I was able to get HomeSite to do that for me through the Tag Dialog for <CFLOOP>. To do this yourself, position yourself on top of the <CFLOOP> tag and choose Edit Tag. The dialog has a checkbox at the bottom that enables you to turn off the Output on a single line option. This helps your code be more readable.

We will now dissect this code. Inside the <TR> tag, you see a <CFLOOP> tag. This tag has a few attributes:

  • INDEX—This attribute holds the value of each item in the list as the loop steps through the list.

  • LIST—A comma-separated list of values; in this case, "Red,Blue,Silver".

  • DELIMITERS—Specifies the character that separates each list value; in this case, the comma (,).

For each value in the list, it will execute the following code:

<CFOUTPUT>
<TD BGCOLOR="#MyColor#">
 <B>#MyColor#</B>
</TD>
</CFOUTPUT>

This will take each color value and use it for the background color of the <TD> tag as well as print out the name of the color. The <CFOUTPUT> tag specifies that the variables need to be resolved to their values. This yields a three-column table with one row because there are three values in the list.

This loop, known as a list loop is used to execute code a number of times equal to the number of values in the list.

TIP

Lists are extremely important to ColdFusion Express developers because the comma delimited list format is used by HTML (for form submissions) and SQL (in IN operators). As such, ColdFusion Express provides a whole family of functions specifically for use in manipulating lists. We'll look at lists in detail in Hour 18.

Using the Index Loop

The index loop allows you to iterate code based on a series of numeric values. To loop ten times and print out the loop number, you would use the following code:

<CFLOOP INDEX="i"
FROM="1"
TO="10" >
Loop number: <CFOUTPUT>#i#</CFOUTPUT><BR>
</CFLOOP>

When this loop is first started, the index variable i (INDEX attribute) is set to the initial value of 1 (FROM attribute). It will go through the following process:

  1. Executes the code inside the <CFLOOP> tag to print out the string "Loop number: 1".

  2. Returns to the opening <CFLOOP> tag and increments INDEX to 2.

  3. Executes the code inside the <CFLOOP> tag to print out "Loop number: 2".

This process is repeated until it goes through the loop for the last time with a value of 10. The output is as shown in Figure 6.6.

Figure 6.6 This index loop will iterate 10 times.

The full syntax of the <CFLOOP> tag for an index loop is shown as follows:

<CFLOOP INDEX="IndexVariable"
FROM="StartValue"
TO="EndValue"
STEP="Increment">

</CFLOOP>

Notice that there is a STEP attribute to this tag. The default is to increment by 1 from the FROM value to the TO value. You can change the increment value by using the STEP attribute. For instance, you can increment by 2:

<CFLOOP INDEX="i"
FROM="1"
TO="10"
STEP="2">
The loop index is <CFOUTPUT>#i#</CFOUTPUT><BR>
</CFLOOP>

This loop will only execute five times, as the output in Figure 6.7 illustrates.

Figure 6.7 This index loop will iterate five times, stepping by 2.

The STEP attribute can also take a negative value, if you want to count backwards. For instance, you can decrement by 1:

<CFLOOP INDEX="i"
FROM="10"
TO="1"
STEP="-1">
The loop index is <CFOUTPUT>#i#</CFOUTPUT><BR>
</CFLOOP>

This loop will only execute 10 times, but will count backwards as the output in Figure 6.8 illustrates.

Figure 6.8 This index loop will iterate 10 times counting backwards.

Looping on a Condition

Whereas the index loop iterates by numeric values, the conditional loop will iterate until a condition is no longer TRUE (becomes FALSE) .

In this loop, you need to determine which condition you want to test, and that condition must yield a TRUE or FALSE outcome.

In the following code example, you will begin by initializing a CountVar variable to 0, and you will test and increment that variable until it exceeds a value of 10:

<!--- Set the variable ConditionVariable to 0 --->
<CFSET ConditionVariable=0>

<!--- Loop until ConditionVariable = 10 --->
<CFLOOP CONDITION="ConditionVariable LESS THAN OR EQUAL TO 10">
<CFSET ConditionVariable=ConditionVariable + 1>
The ConditionVariable is <CFOUTPUT>#ConditionVariable#</CFOUTPUT>.<BR>
</CFLOOP>

Notice in this example that the loop will run 11 times, as Figure 6.9 shows. This loop executes 11 times because it is counting from 0 to 10, inclusive, which is 11 times.

Figure 6.9 This conditional loop will iterate 11 times.

Does the logical operator—LESS THAN OR EQUAL TO—look familiar? It should. All the same operators that apply to the <CFIF> tag also apply to the conditional loop.

CAUTION

Don't forget that all loops must come to an end. If you incorrectly form your condition, it might never reach a FALSE result and therefore will never end. If this happens, it's called an endless loop. Kinda like the directions on the shampoo bottle—lather, rinse, repeat—it never tells you when to stop.

Using <CFLOOP> to Create a Color Palette

We will look at an application of using the <CFLOOP> tag. To set this up, you must understand the colors available to the Web.

HTML has two ways to refer to colors, by name (for example, red or green), or by RGB value (for example, #FF0000 and #00FF00). The RGB value format is more powerful—it supports a far greater range of colors and far more browsers. This color palette is known as the Browser Safety Palette, which should be supported by most browsers.

To Do: Looping to Create the Browser Safety Palette

View the Browser Safety Palette in HomeSite by performing the following steps:

  1. Launch HomeSite

  2. On the main toolbar, choose the Palette option.

  3. You will see the Browser Safety Palette as shown in Figure 6.10. Move the mouse over the colors, and you will see the hexadecimal value for each.

Figure 6.10 HomeSite's Browser Safety Palette can be displayed by choosing the palette toolbar item on the main toolbar.

The RGB number is made up of hexadecimal numbers from black (#000000) to white (#FFFFFF). You can build all the colors in between by using a combination of hexadecimal pairs—00,33,66,99,cc,ff. If you combine each of these pairs with the others into six-digit hexadecimal numbers, you will find every RGB color available.

For instance, you can concatenate three pairs in this order:

00 & 00 & 00 = 000000
00 & 00 & 33 = 000033
00 & 00 & 66 = 000066
00 & 00 & 99 = 000099
00 & 00 & cc = 0000cc
00 & 00 & ff = 0000ff
00 & 33 & 00 = 003300
00 & 33 & 33 = 003333

If you were to continue and combine each pair with the other, all colors in the palette would be created. To do this, you can create three nested loops:

<CFSET hex="00,33,66,99,cc,ff">
<CFLOOP INDEX="Red" LIST="#hex#">
 <CFLOOP INDEX="Green" LIST="#hex#">
  <CFLOOP INDEX="Blue" LIST="#hex#">
   <CFSET RGB=Red & Green & Blue>
   <CFOUTPUT>#RGB#</CFOUTPUT><BR>
  </CFLOOP>
 </CFLOOP>
</CFLOOP>

Each of the three pairs of digits are concatenated together using the ampersand (&) into one RGB variable. Figure 6.11 shows some of the output for this code.

Figure 6.11 Nested loops can be used to construct strings.

Next we will use the generated RGB number as the background color of a table cell; one for each RGB number generated as shown in Listing 6.1.

Listing 6.1 Using CFLOOP to Produce the Browser Safety Palette

 1:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
 2:
 3:<HTML>
 4:<HEAD>
 5: <TITLE>Using CFLOOP to produce the Browser Safety Palette</TITLE>
 6:</HEAD>
 7:
 8:<BODY>
 9:
10:<!--- set hex pairs --->
11:<CFSET hex="00,33,66,99,cc,ff">
12:
13:<!--- loop through each list of hex pairs--->
14:<TABLE>
15:<CFLOOP INDEX="Red" LIST="#hex#">
16: <CFLOOP INDEX="Green" LIST="#hex#">
17:  <TR>
18:  <CFLOOP INDEX="Blue" LIST="#hex#">
19:  <CFSET RGB= Red & Green & Blue>
20:  <CFOUTPUT><TD BGCOLOR="#RGB#"
21:      WIDTH="100"
22:      ALIGN="center">#RGB#
23:     </TD>
24:  </CFOUTPUT>
25:  </CFLOOP>
26:  </TR>
27: </CFLOOP>
28:</CFLOOP>
29:</TABLE>
30:
31:</BODY>
32:</HTML>

Each color in the Browser Safety Palette is now displayed in a table, as shown in Figure 6.12.

Figure 6.12 You can create the Browser Safety Palette using three nested loops.

This is just one of the many reasons to use the <CFLOOP> tag.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020