- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.
Syntax
index = "parameter name" from = "beginning value" to = "ending value" step = "increment" charset "charset to read in a file"> HTML or CFML code ... </cfloop>
See also
cfabort, cfbreak, cfcontinue, cfdirectory, cfexecute, cfexit, cfif, cflocation, cfrethrow, cfswitch, cfthrow, cftry; cfloop and
cfbreak in the Developing ColdFusion Applications
Attributes
Attribute |
Req/Opt |
Default |
Description |
|---|---|---|---|
index |
Required |
|
Index value. ColdFusion sets it to the from value and increments or decrements by step value, until it equals the to value. |
from |
Required |
|
Beginning value of index. |
to |
Required |
|
Ending value of index. |
step |
Optional |
1 |
Step by which to increment or decrement the index value. |
charset |
optional |
|
Charset to use when reading in a file line-by-line. |
Usage
Using anything other than integer values in the from and to attributes of an index loop can product unexpected results. For example, if you increment through an index loop from 1 to 2, with a step of 0.1, ColdFusion outputs "1,1.1,1.2,...,1.9", but not "2". This is a programming language problem regarding the internal representation of floating point numbers.
The to value is evaluated once, when the cfloop tag is encountered. Any change to this value within the loop block, or within the expression that evaluates to this value, does not affect the number of times the loop is executed.
Example
<cfloop index="i" from="1" to="5" >
The loop index is <cfoutput>#i#</cfoutput>.<br>
</cfloop>
The output of this loop is as follows:
The loop index is 1. The loop index is 2. The loop index is 3. The loop index is 4. The loop index is 5.
<cfset j=5/>
<cfloop index = "LoopCount" from = "1" to = #j#>
<cfoutput>The loop index is #LoopCount#</cfoutput>.<br/>
<cfset j = j - 1>
</cfloop>
The output of this loop is as follows:
The loop index is 1. The loop index is 2. The loop index is 3. The loop index is 4. The loop index is 5.
<cfloop index = "LoopCount"
from = "5"
to = "1"
step = "-1">
The loop index is <cfoutput>#LoopCount#</cfoutput>.<br/>
</cfloop>
The output of this loop is as follows:
The loop index is 5. The loop index is 4. The loop index is 3. The loop index is 2. The loop index is 1.
Real-world uses of the cfloop tag
Batch processing- Email queue system
Your email marketing platform has a queue of 10,000 emails that need to be sent. To avoid overwhelming the mail server and to comply with rate limits, you need to process emails in batches of 50. Additionally, you need to implement delays between batches, track progress, and handle failures gracefully.
Problem statement
- Large email queue requires batch processing
- Mail server has rate limits (e.g., 50 emails per minute)
- Need to process records in fixed-size chunks
- Must track which batch is currently processing
- Implement delays between batches to avoid throttling
Solution
Use cfloop with `index`, `from`, `to`, and `step` attributes.
<cfscript>
// Simulate email queue (in production, this would be from database)
totalEmails = 237; // Example: 237 emails in queue
batchSize = 50;
// Calculate total batches needed
totalBatches = ceiling(totalEmails / batchSize);
// Track processing
startBatch = isDefined("url.startBatch") AND isNumeric(url.startBatch) ? url.startBatch : 1;
processedCount = 0;
failedCount = 0;
// Generate sample email queue
emailQueue = [];
for (i = 1; i <= totalEmails; i++) {
arrayAppend(emailQueue, {
id: i,
email: "user#i#@example.com",
subject: "Newsletter ##" & i,
status: "pending"
});
}
</cfscript>
<h2>📧 Email Queue Batch Processing System</h2>
<div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 15px; margin: 20px 0; border-radius: 5px;">
<strong>Queue Summary:</strong><br>
<cfoutput>
Total Emails: #totalEmails# |
Batch Size: #batchSize# |
Total Batches: #totalBatches# |
Starting from Batch: #startBatch#
</cfoutput>
</div>
<!--- Process form submission --->
<cfif isDefined("form.action") AND form.action EQ "process">
<h3>🔄 Processing Email Batches...</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; margin: 20px 0; border-radius: 5px;">
<!--- INDEX LOOP: Process batches from startBatch to totalBatches --->
<cfloop index="batchNum" from="#startBatch#" to="#totalBatches#">
<cfscript>
// Calculate start and end indices for this batch
batchStartIndex = (batchNum - 1) * batchSize + 1;
batchEndIndex = min(batchNum * batchSize, totalEmails);
batchEmailCount = batchEndIndex - batchStartIndex + 1;
// Track batch results
batchSuccess = 0;
batchFailed = 0;
</cfscript>
<!--- Batch Header --->
<div style="background: ##2196f3; color: white; padding: 10px; margin: 15px 0 5px 0; border-radius: 5px;">
<cfoutput>
<strong>Batch #batchNum# of #totalBatches#</strong> -
Processing emails #batchStartIndex# to #batchEndIndex# (#batchEmailCount# emails)
</cfoutput>
</div>
<div style="padding: 10px; background: ##f5f5f5; margin-bottom: 15px;">
<!--- INDEX LOOP: Process individual emails in this batch --->
<cfloop index="emailIndex" from="#batchStartIndex#" to="#batchEndIndex#">
<cfscript>
email = emailQueue[emailIndex];
// Simulate email sending (90% success rate)
sendSuccess = randRange(1, 10) GT 1;
if (sendSuccess) {
batchSuccess++;
processedCount++;
} else {
batchFailed++;
failedCount++;
}
</cfscript>
<cfoutput>
<div style="padding: 5px; font-size: 12px; color: ##666;">
#sendSuccess ? '✓' : '✗'#
Email ##i##: #email.email# -
<span style="color: #sendSuccess ? '##4caf50' : '##f44336'#;">
#sendSuccess ? 'Sent' : 'Failed'#
</span>
</div>
</cfoutput>
</cfloop>
<!--- Batch Summary --->
<div style="margin-top: 10px; padding: 10px; background: ##fff3e0; border-radius: 3px;">
<cfoutput>
<strong>Batch #batchNum# Complete:</strong>
#batchSuccess# sent, #batchFailed# failed
</cfoutput>
</div>
</div>
<!--- Simulate delay between batches (in production, use sleep()) --->
<cfoutput>
<div style="padding: 5px; color: ##999; font-size: 12px; font-style: italic;">
⏱ Waiting 60 seconds before next batch... (rate limiting)
</div>
</cfoutput>
</cfloop>
</div>
<!--- Final Summary --->
<div style="background: ##4caf50; color: white; padding: 20px; margin: 20px 0; border-radius: 5px; text-align: center;">
<h3 style="margin: 0;">✓ Processing Complete!</h3>
<cfoutput>
<p style="font-size: 18px; margin: 10px 0;">
<strong>#processedCount#</strong> emails sent successfully<br>
<strong>#failedCount#</strong> emails failed
</p>
</cfoutput>
</div>
<p>
<a href="?" style="padding: 10px 20px; background: ##2196f3; color: white; text-decoration: none; border-radius: 5px; display: inline-block;">
← Back to Queue
</a>
</p>
<cfelse>
<!--- Display batch preview --->
<h3>Batch Preview</h3>
<table style="width: 100%; border-collapse: collapse; margin: 20px 0; background: white;">
<thead>
<tr style="background: ##2196f3; color: white;">
<th style="padding: 10px; border: 1px solid ##ddd;">Batch ##</th>
<th style="padding: 10px; border: 1px solid ##ddd;">Start Index</th>
<th style="padding: 10px; border: 1px solid ##ddd;">End Index</th>
<th style="padding: 10px; border: 1px solid ##ddd;">Email Count</th>
</tr>
</thead>
<tbody>
<!--- INDEX LOOP: Display batch information --->
<cfloop index="batchNum" from="1" to="#totalBatches#">
<cfscript>
batchStart = (batchNum - 1) * batchSize + 1;
batchEnd = min(batchNum * batchSize, totalEmails);
emailCount = batchEnd - batchStart + 1;
</cfscript>
<cfoutput>
<tr #batchNum MOD 2 EQ 0 ? 'style="background: ##f5f5f5;"' : ''#>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center; font-weight: bold;">
#batchNum#
</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">
#batchStart#
</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">
#batchEnd#
</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">
#emailCount# emails
</td>
</tr>
</cfoutput>
</cfloop>
</tbody>
</table>
<!--- Processing Options --->
<div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h3 style="margin-top: 0;">Processing Options</h3>
<form method="post">
<input type="hidden" name="action" value="process">
<div style="margin: 15px 0;">
<label for="startBatch"><strong>Start from Batch:</strong></label><br>
<select name="startBatch" id="startBatch" style="padding: 8px; width: 200px;">
<cfloop index="i" from="1" to="#totalBatches#">
<cfoutput>
<option value="#i#">Batch #i#</option>
</cfoutput>
</cfloop>
</select>
<p style="color: ##666; font-size: 14px; margin: 5px 0;">
Useful for resuming after interruption
</p>
</div>
<div style="margin: 20px 0;">
<button type="submit" style="padding: 15px 30px; background: ##4caf50; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; font-weight: bold;">
▶ Start Batch Processing
</button>
</div>
</form>
</div>
</cfif>
<!--- Example: Process Every Nth Item --->
<div style="margin: 40px 0;">
<h3>Example 2: Process Every 10th Email (Sampling)</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; border-radius: 5px;">
<p>Sometimes you need to process every Nth item for sampling or testing. Use the <code>step</code> attribute:</p>
<div style="background: ##f5f5f5; padding: 15px; border-radius: 5px; margin: 15px 0;">
<!--- INDEX LOOP with STEP: Process every 10th item --->
<cfloop index="i" from="1" to="#min(100, totalEmails)#" step="10">
<cfoutput>
<div style="padding: 5px;">
📊 Sample email ##i##: #emailQueue[i].email#
</div>
</cfoutput>
</cfloop>
</div>
<p style="color: ##666; font-size: 14px;">
<strong>Use case:</strong> Quality assurance sampling, A/B testing groups, performance testing
</p>
</div>
</div>
<!--- Example: Reverse Processing --->
<div style="margin: 40px 0;">
<h3>Example 3: Reverse Order Processing (LIFO Queue)</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; border-radius: 5px;">
<p>Process items in reverse order (Last In, First Out) using negative step:</p>
<div style="background: ##f5f5f5; padding: 15px; border-radius: 5px; margin: 15px 0;">
<!--- INDEX LOOP: Reverse iteration with step="-1" --->
<cfloop index="i" from="#min(10, totalEmails)#" to="1" step="-1">
<cfoutput>
<div style="padding: 5px;">
⬅ Processing email ##i##: #emailQueue[i].email# (reverse order)
</div>
</cfoutput>
</cfloop>
</div>
<p style="color: ##666; font-size: 14px;">
<strong>Use case:</strong> Stack processing, priority queues, undo operations
</p>
</div>
</div>
Calendar generation system
Your event management application needs to display monthly calendars for users to book appointments, schedule meetings, and view events. The calendar must show all days of the month in a grid format with proper week structure (Sunday-Saturday), handle different month lengths, and highlight special dates.
Problem statement
- Need to generate calendar grids dynamically
- Must handle varying month lengths (28, 29, 30, 31 days)
- Display weeks in rows (7 days per row)
- Calculate day-of-week for first day of month
- Fill in empty cells before/after month days
Solution
Use nested cfloop with `index` attributes.
<cfscript>
// Get current date or specified date
if (isDefined("url.year") AND isDefined("url.month")) {
targetYear = url.year;
targetMonth = url.month;
} else {
targetYear = year(now());
targetMonth = month(now());
}
// Create first day of target month
firstDayOfMonth = createDate(targetYear, targetMonth, 1);
// Get calendar information
monthName = monthAsString(targetMonth);
daysInMonth = daysInMonth(firstDayOfMonth);
firstDayOfWeek = dayOfWeek(firstDayOfMonth); // 1=Sunday, 7=Saturday
// Calculate total cells needed (weeks * 7)
totalCells = 42; // 6 weeks * 7 days (maximum possible)
weeksToShow = 6;
// Today's date for highlighting
today = now();
isCurrentMonth = (year(today) EQ targetYear AND month(today) EQ targetMonth);
currentDay = day(today);
// Sample events (in production, query from database)
events = {
"5": [{title: "Team Meeting", time: "10:00 AM"}],
"12": [{title: "Project Deadline", time: "5:00 PM"}],
"15": [{title: "Client Review", time: "2:00 PM"}],
"20": [{title: "Conference", time: "9:00 AM"}],
"25": [{title: "Holiday", time: "All Day"}]
};
// Previous/Next month navigation
prevMonth = dateAdd("m", -1, firstDayOfMonth);
nextMonth = dateAdd("m", 1, firstDayOfMonth);
</cfscript>
<h2>📅 Calendar: <cfoutput>#monthName# #targetYear#</cfoutput></h2>
<!--- Calendar Navigation --->
<div style="text-align: center; margin: 20px 0;">
<cfoutput>
<a href="?year=#year(prevMonth)#&month=#month(prevMonth)#" style="padding: 8px 15px; background: ##2196f3; color: white; text-decoration: none; border-radius: 3px; margin: 0 10px;">
« #monthAsString(month(prevMonth))#
</a>
<span style="padding: 8px 15px; background: ##4caf50; color: white; border-radius: 3px; font-weight: bold;">
#monthName# #targetYear#
</span>
<a href="?year=#year(nextMonth)#&month=#month(nextMonth)#" style="padding: 8px 15px; background: ##2196f3; color: white; text-decoration: none; border-radius: 3px; margin: 0 10px;">
#monthAsString(month(nextMonth))# »
</a>
</cfoutput>
</div>
<!--- Calendar Grid --->
<table style="width: 100%; border-collapse: collapse; margin: 20px 0; background: white; border: 2px solid ##333;">
<!--- Day of Week Headers --->
<thead>
<tr style="background: ##2196f3; color: white;">
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Sunday</th>
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Monday</th>
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Tuesday</th>
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Wednesday</th>
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Thursday</th>
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Friday</th>
<th style="padding: 15px; border: 1px solid ##ddd; text-align: center; width: 14.28%;">Saturday</th>
</tr>
</thead>
<tbody>
<!--- OUTER INDEX LOOP: Iterate through weeks (0-5) --->
<cfloop index="week" from="0" to="#weeksToShow-1#">
<tr>
<!--- INNER INDEX LOOP: Iterate through days of week (1-7) --->
<cfloop index="dayOfWeek" from="1" to="7">
<cfscript>
// Calculate cell position (1-42)
cellPosition = week * 7 + dayOfWeek;
// Calculate actual day number
dayNumber = cellPosition - firstDayOfWeek + 1;
// Determine if this cell should display a day
isValidDay = (dayNumber GTE 1 AND dayNumber LTE daysInMonth);
// Check if weekend
isWeekend = (dayOfWeek EQ 1 OR dayOfWeek EQ 7); // Sunday or Saturday
// Check if today
isToday = (isCurrentMonth AND isValidDay AND dayNumber EQ currentDay);
// Check if has event
hasEvent = isValidDay AND structKeyExists(events, toString(dayNumber));
// Determine cell style
if (NOT isValidDay) {
cellStyle = "background: ##f5f5f5; color: ##ccc;";
} else if (isToday) {
cellStyle = "background: ##4caf50; color: white; font-weight: bold;";
} else if (isWeekend) {
cellStyle = "background: ##e3f2fd;";
} else if (hasEvent) {
cellStyle = "background: ##fff3e0;";
} else {
cellStyle = "background: white;";
}
</cfscript>
<cfoutput>
<td style="#cellStyle# padding: 10px; border: 1px solid ##ddd; vertical-align: top; height: 100px;">
<cfif isValidDay>
<div style="font-size: 18px; font-weight: bold; margin-bottom: 5px;">
#dayNumber#
<cfif isToday>
<span style="font-size: 10px; background: white; color: ##4caf50; padding: 2px 5px; border-radius: 3px; margin-left: 5px;">
Today
</span>
</cfif>
</div>
<!--- Display events for this day --->
<cfif hasEvent>
<cfloop array="#events[toString(dayNumber)]#" index="event">
<div style="font-size: 11px; background: ##ff9800; color: white; padding: 3px 5px; margin: 2px 0; border-radius: 3px;">
<strong>#event.title#</strong><br>
#event.time#
</div>
</cfloop>
</cfif>
<cfelse>
</cfif>
</td>
</cfoutput>
</cfloop>
</tr>
</cfloop>
</tbody>
</table>
<!--- Calendar Legend --->
<div style="background: ##f5f5f5; border: 1px solid ##ccc; padding: 15px; margin: 20px 0; border-radius: 5px;">
<h4 style="margin-top: 0;">Calendar Legend</h4>
<div style="display: flex; gap: 20px; flex-wrap: wrap;">
<div style="display: flex; align-items: center;">
<div style="width: 30px; height: 30px; background: ##4caf50; border: 1px solid ##333; margin-right: 10px;"></div>
<span>Today</span>
</div>
<div style="display: flex; align-items: center;">
<div style="width: 30px; height: 30px; background: ##e3f2fd; border: 1px solid ##333; margin-right: 10px;"></div>
<span>Weekend</span>
</div>
<div style="display: flex; align-items: center;">
<div style="width: 30px; height: 30px; background: ##fff3e0; border: 1px solid ##333; margin-right: 10px;"></div>
<span>Has Events</span>
</div>
</div>
</div>
<!--- Example: Compact Calendar (3-Month View) --->
<div style="margin: 40px 0;">
<h3>Example 2: Three-Month View</h3>
<div style="display: flex; gap: 20px; justify-content: space-between;">
<!--- INDEX LOOP: Generate 3 months --->
<cfloop index="monthOffset" from="-1" to="1">
<cfscript>
compactDate = dateAdd("m", monthOffset, firstDayOfMonth);
compactYear = year(compactDate);
compactMonth = month(compactDate);
compactMonthName = monthAsString(compactMonth);
compactFirstDay = createDate(compactYear, compactMonth, 1);
compactDaysInMonth = daysInMonth(compactFirstDay);
compactFirstDayOfWeek = dayOfWeek(compactFirstDay);
</cfscript>
<cfoutput>
<div style="flex: 1; background: white; border: 1px solid ##ddd; padding: 10px; border-radius: 5px;">
<h4 style="text-align: center; margin: 0 0 10px 0; color: ##2196f3;">
#compactMonthName# #compactYear#
</h4>
<table style="width: 100%; border-collapse: collapse; font-size: 11px;">
<thead>
<tr style="background: ##e0e0e0;">
<th style="padding: 5px;">S</th>
<th style="padding: 5px;">M</th>
<th style="padding: 5px;">T</th>
<th style="padding: 5px;">W</th>
<th style="padding: 5px;">T</th>
<th style="padding: 5px;">F</th>
<th style="padding: 5px;">S</th>
</tr>
</thead>
<tbody>
<!--- Compact calendar weeks --->
<cfloop index="wk" from="0" to="5">
<tr>
<cfloop index="dw" from="1" to="7">
<cfset cp = wk * 7 + dw>
<cfset dn = cp - compactFirstDayOfWeek + 1>
<cfset valid = (dn GTE 1 AND dn LTE compactDaysInMonth)>
<td style="padding: 5px; text-align: center; border: 1px solid ##eee; #NOT valid ? 'color: ##ccc;' : ''#">
#valid ? dn : ''#
</td>
</cfloop>
</tr>
</cfloop>
</tbody>
</table>
</div>
</cfoutput>
</cfloop>
</div>
</div>
<!--- Example: Year Overview --->
<div style="margin: 40px 0;">
<h3>Example 3: Year Overview Grid</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; border-radius: 5px;">
<cfoutput>
<h4 style="text-align: center;">#targetYear# Calendar</h4>
</cfoutput>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px;">
<!--- INDEX LOOP: All 12 months --->
<cfloop index="m" from="1" to="12">
<cfscript>
yearMonthDate = createDate(targetYear, m, 1);
yearMonthName = monthAsString(m);
yearDaysInMonth = daysInMonth(yearMonthDate);
</cfscript>
<cfoutput>
<div style="border: 1px solid ##ddd; padding: 10px; border-radius: 5px;">
<h5 style="text-align: center; margin: 0 0 10px 0; color: ##2196f3;">
#yearMonthName#
</h5>
<div style="text-align: center; font-size: 24px; font-weight: bold; color: ##666;">
#yearDaysInMonth# days
</div>
</div>
</cfoutput>
</cfloop>
</div>
</div>
</div>
Generate chart data for analytics
Your business intelligence dashboard needs to display various charts and graphs showing sales trends, user growth, performance metrics, and financial data. Charts require data points at specific intervals (hourly, daily, monthly) with consistent x-axis values. You need to generate sample data for testing, fill in missing data points, and create smooth data series for visualization libraries.
Problem statement
- Charts need data points at regular intervals
- Must generate sequential x-axis values (0-100, Jan-Dec, etc.)
- Need to fill gaps in sparse data
- Generate sample/mock data for development
- Create smooth data series for trend lines
Solution
Use cfloop with `index` for systematic data generation.
<cfscript>
// Generate sales data for 12 months
salesData = [];
revenueData = [];
months = [];
// INDEX LOOP: Generate monthly data
cfloop(index="monthNum", from="1", to="12") {
// Add month name
arrayAppend(months, monthAsString(monthNum));
// Generate sales with upward trend + randomness
baseSales = 100 + (monthNum * 20);
salesVariation = randRange(-15, 30);
monthlySales = baseSales + salesVariation;
arrayAppend(salesData, monthlySales);
// Generate revenue (sales * average price)
monthlyRevenue = monthlySales * randRange(45, 55);
arrayAppend(revenueData, monthlyRevenue);
}
// Calculate totals
totalSales = arraySum(salesData);
totalRevenue = arraySum(revenueData);
</cfscript>
<h2>📊 Analytics Dashboard - Chart Data Generation</h2>
<!--- Chart 1: Monthly Sales Line Chart --->
<div style="background: white; border: 2px solid ##2196f3; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h3>Monthly Sales Trend</h3>
<!--- Simple ASCII Bar Chart --->
<div style="background: ##f5f5f5; padding: 20px; border-radius: 5px;">
<cfloop index="i" from="1" to="12">
<cfset barWidth = (salesData[i] / arrayMax(salesData)) * 100>
<cfoutput>
<div style="margin: 8px 0;">
<div style="display: inline-block; width: 80px; font-weight: bold;">
#months[i]#:
</div>
<div style="display: inline-block; width: #barWidth#%; background: ##2196f3; color: white; padding: 5px 10px; border-radius: 3px;">
#salesData[i]# units
</div>
</div>
</cfoutput>
</cfloop>
</div>
<!--- Chart Data as JSON --->
<div style="margin: 20px 0;">
<h4>Chart.js Compatible Data:</h4>
<cfscript>
chartData = {
labels: months,
datasets: [
{
label: "Monthly Sales",
data: salesData,
backgroundColor: "##2196f3",
borderColor: "##1976d2",
borderWidth: 2
}
]
};
</cfscript>
<pre style="background: ##263238; color: ##aed581; padding: 15px; border-radius: 5px; overflow-x: auto; font-size: 12px;"><cfoutput>#serializeJSON(chartData)#</cfoutput></pre>
</div>
</div>
<!--- Chart 2: Percentage Progress Bars --->
<div style="background: white; border: 2px solid ##4caf50; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h3>Team Performance Metrics</h3>
<cfscript>
teams = [
{name: "Sales Team", target: 100, achieved: 87},
{name: "Marketing Team", target: 100, achieved: 94},
{name: "Development Team", target: 100, achieved: 78},
{name: "Support Team", target: 100, achieved: 99}
];
</cfscript>
<cfloop array="#teams#" index="team">
<cfoutput>
<div style="margin: 20px 0;">
<div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
<strong>#team.name#</strong>
<span>#team.achieved#%</span>
</div>
<!--- Progress bar background --->
<div style="background: ##e0e0e0; height: 30px; border-radius: 15px; overflow: hidden; position: relative;">
<!--- Progress bar fill --->
<div style="background: ##4caf50; height: 100%; width: #team.achieved#%; transition: width 0.3s;"></div>
<!--- Goal markers using INDEX LOOP --->
<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
<cfloop index="marker" from="0" to="100" step="25">
<div style="position: absolute; left: #marker#%; top: 0; bottom: 0; width: 2px; background: ##999; opacity: 0.3;"></div>
<div style="position: absolute; left: #marker#%; top: -20px; font-size: 10px; color: ##666; transform: translateX(-50%);">
#marker#%
</div>
</cfloop>
</div>
</div>
</div>
</cfoutput>
</cfloop>
</div>
<!--- Chart 3: Cumulative Growth Chart --->
<div style="background: white; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h3>Cumulative User Growth</h3>
<cfscript>
// Generate cumulative data using INDEX LOOP
weeklyNewUsers = [];
cumulativeUsers = [];
weeks = [];
runningTotal = 0;
cfloop(index="week", from="1", to="12") {
// Generate weekly new users
newUsers = randRange(50, 150);
arrayAppend(weeklyNewUsers, newUsers);
// Calculate cumulative total
runningTotal += newUsers;
arrayAppend(cumulativeUsers, runningTotal);
arrayAppend(weeks, "Week " & week);
}
</cfscript>
<table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
<thead>
<tr style="background: ##ff9800; color: white;">
<th style="padding: 10px; border: 1px solid ##ddd;">Week</th>
<th style="padding: 10px; border: 1px solid ##ddd;">New Users</th>
<th style="padding: 10px; border: 1px solid ##ddd;">Cumulative Total</th>
<th style="padding: 10px; border: 1px solid ##ddd;">Visual</th>
</tr>
</thead>
<tbody>
<cfloop index="i" from="1" to="12">
<cfoutput>
<tr #i MOD 2 EQ 0 ? 'style="background: ##f5f5f5;"' : ''#>
<td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">#weeks[i]#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">+#weeklyNewUsers[i]#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center; font-weight: bold; color: ##ff9800;">#cumulativeUsers[i]#</td>
<td style="padding: 10px; border: 1px solid ##ddd;">
<div style="width: #(cumulativeUsers[i] / arrayMax(cumulativeUsers)) * 100#%; background: ##ff9800; height: 20px; border-radius: 3px;"></div>
</td>
</tr>
</cfoutput>
</cfloop>
</tbody>
</table>
</div>
<!--- Example: Hourly Data Points --->
<div style="margin: 40px 0;">
<h3>Example 2: Hourly Website Traffic (24 Hours)</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; border-radius: 5px;">
<cfscript>
hourlyTraffic = [];
hours = [];
// INDEX LOOP: Generate data for each hour
cfloop(index="hour", from="0", to="23") {
// Traffic pattern: higher during business hours
if (hour GTE 9 AND hour LTE 17) {
traffic = randRange(400, 600); // Business hours
} else if (hour GTE 6 AND hour LTE 8) {
traffic = randRange(200, 300); // Morning
} else if (hour GTE 18 AND hour LTE 22) {
traffic = randRange(250, 400); // Evening
} else {
traffic = randRange(50, 150); // Night
}
arrayAppend(hourlyTraffic, traffic);
arrayAppend(hours, numberFormat(hour, "00") & ":00");
}
</cfscript>
<div style="display: flex; align-items: flex-end; height: 200px; gap: 5px; padding: 20px; background: ##f5f5f5; border-radius: 5px;">
<cfloop index="i" from="1" to="24">
<cfset barHeight = (hourlyTraffic[i] / arrayMax(hourlyTraffic)) * 100>
<cfoutput>
<div style="flex: 1; display: flex; flex-direction: column; align-items: center;">
<div style="background: ##2196f3; width: 100%; height: #barHeight#%; min-height: 20px; border-radius: 3px 3px 0 0;" title="#hours[i]#: #hourlyTraffic[i]# visits"></div>
<div style="font-size: 9px; margin-top: 5px; transform: rotate(-45deg); white-space: nowrap;">
#listFirst(hours[i], ":")#h
</div>
</div>
</cfoutput>
</cfloop>
</div>
<cfoutput>
<p style="text-align: center; margin-top: 20px;">
<strong>Total Daily Visits:</strong> #numberFormat(arraySum(hourlyTraffic))# |
<strong>Peak Hour:</strong> #hours[arrayFind(hourlyTraffic, arrayMax(hourlyTraffic))]# (#arrayMax(hourlyTraffic)# visits)
</p>
</cfoutput>
</div>
</div>
<!--- Example: Multi-Series Comparison --->
<div style="margin: 40px 0;">
<h3>Example 3: Multi-Series Comparison (Q1-Q4)</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; border-radius: 5px;">
<cfscript>
quarters = ["Q1", "Q2", "Q3", "Q4"];
year2023 = [];
year2024 = [];
// INDEX LOOP: Generate data for each quarter
cfloop(index="q", from="1", to="4") {
// 2023 data
arrayAppend(year2023, randRange(80, 120));
// 2024 data (growth trend)
arrayAppend(year2024, randRange(100, 150));
}
</cfscript>
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background: ##2196f3; color: white;">
<th style="padding: 12px; border: 1px solid ##ddd;">Quarter</th>
<th style="padding: 12px; border: 1px solid ##ddd;">2023 Sales</th>
<th style="padding: 12px; border: 1px solid ##ddd;">2024 Sales</th>
<th style="padding: 12px; border: 1px solid ##ddd;">Growth</th>
</tr>
</thead>
<tbody>
<cfloop index="i" from="1" to="4">
<cfset growth = ((year2024[i] - year2023[i]) / year2023[i]) * 100>
<cfoutput>
<tr>
<td style="padding: 12px; border: 1px solid ##ddd; font-weight: bold;">#quarters[i]#</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: right;">#numberFormat(year2023[i])#K</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: right;">#numberFormat(year2024[i])#K</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: right; color: #growth GT 0 ? '##4caf50' : '##f44336'#; font-weight: bold;">
#growth GT 0 ? '+' : ''##numberFormat(growth, "0.0")#%
</td>
</tr>
</cfoutput>
</cfloop>
</tbody>
</table>
</div>
</div>
<!--- Data Generation Summary --->
<div style="background: ##f5f5f5; border: 1px solid ##ccc; padding: 15px; margin: 20px 0; border-radius: 5px;">
<h3>Data Generation Summary</h3>
<cfoutput>
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 10px; border: 1px solid ##ccc; font-weight: bold;">Monthly Sales Data Points:</td>
<td style="padding: 10px; border: 1px solid ##ccc;">#arrayLen(salesData)#</td>
</tr>
<tr>
<td style="padding: 10px; border: 1px solid ##ccc; font-weight: bold;">Total Sales (Year):</td>
<td style="padding: 10px; border: 1px solid ##ccc;">#totalSales# units</td>
</tr>
<tr>
<td style="padding: 10px; border: 1px solid ##ccc; font-weight: bold;">Total Revenue (Year):</td>
<td style="padding: 10px; border: 1px solid ##ccc;">#dollarFormat(totalRevenue)#</td>
</tr>
<tr>
<td style="padding: 10px; border: 1px solid ##ccc; font-weight: bold;">Hourly Data Points:</td>
<td style="padding: 10px; border: 1px solid ##ccc;">#arrayLen(hourlyTraffic)# (24 hours)</td>
</tr>
<tr>
<td style="padding: 10px; border: 1px solid ##ccc; font-weight: bold;">Cumulative Growth Points:</td>
<td style="padding: 10px; border: 1px solid ##ccc;">#arrayLen(cumulativeUsers)# weeks</td>
</tr>
</table>
</cfoutput>
</div>
Seat reservation system
Your theater/cinema/airline booking system needs to display seat maps for customers to select their seats. Seats are arranged in rows and columns, each with a unique number. The system must show available seats, reserved seats, and selected seats with clear visual indicators. Seats need sequential numbering for easy reference.
Problem statement
- Need to generate grid of seats (rows × columns)
- Each seat requires unique identification
- Sequential numbering across rows (1, 2, 3...)
- Or row-based numbering (A1, A2, B1, B2...)
- Visual distinction of seat states (available, reserved, selected)
- Support different seating layouts (standard, premium, VIP)
Solution
Use nested cfloop with `index` for systematic seat generation.
<cfscript>
// Seating configuration
totalRows = 8;
seatsPerRow = 10;
totalSeats = totalRows * seatsPerRow;
// Pricing tiers based on row
function getSeatPrice(row) {
if (row LTE 2) {
return 50; // Premium front rows
} else if (row LTE 5) {
return 35; // Standard middle rows
} else {
return 25; // Economy back rows
}
}
// Simulate reserved seats (in production, query from database)
reservedSeats = "A3,A4,B5,B6,C7,D2,D3,D4,E8,E9,F10,G1,G2";
// Track selected seats (from session or URL)
selectedSeats = isDefined("form.selectedSeats") ? form.selectedSeats : "";
// Row letters
rowLetters = ["A", "B", "C", "D", "E", "F", "G", "H"];
</cfscript>
<h2>🎬 Movie Theater - Seat Selection</h2>
<div style="background: ##e3f2fd; border: 2px solid ##2196f3; padding: 15px; margin: 20px 0; border-radius: 5px;">
<strong>Movie:</strong> The ColdFusion Chronicles |
<strong>Show Time:</strong> 7:30 PM |
<strong>Theater:</strong> Hall 1
</div>
<!--- Screen --->
<div style="background: ##333; color: white; text-align: center; padding: 20px; margin: 20px 0; border-radius: 5px 5px 0 0;">
<h3 style="margin: 0;">📺 SCREEN</h3>
</div>
<!--- Seat Map --->
<form method="post">
<div style="background: ##f5f5f5; padding: 30px; border-radius: 5px; overflow-x: auto;">
<table style="margin: 0 auto; border-collapse: separate; border-spacing: 5px;">
<!--- Column Headers (Seat Numbers) --->
<thead>
<tr>
<th style="padding: 10px;"></th>
<!--- INDEX LOOP: Seat column headers --->
<cfloop index="seatNum" from="1" to="#seatsPerRow#">
<cfoutput>
<th style="padding: 5px; text-align: center; color: ##666; font-size: 12px;">
#seatNum#
</th>
</cfoutput>
</cfloop>
</tr>
</thead>
<tbody>
<!--- OUTER INDEX LOOP: Rows --->
<cfloop index="row" from="1" to="#totalRows#">
<cfset rowLetter = rowLetters[row]>
<cfset seatPrice = getSeatPrice(row)>
<tr>
<!--- Row Label --->
<cfoutput>
<td style="padding: 10px; font-weight: bold; color: ##666; font-size: 14px;">
Row #rowLetter#
</td>
</cfoutput>
<!--- INNER INDEX LOOP: Seats in this row --->
<cfloop index="seatNum" from="1" to="#seatsPerRow#">
<cfscript>
// Generate seat ID
seatID = rowLetter & seatNum;
// Check seat status
isReserved = listFindNoCase(reservedSeats, seatID) GT 0;
isSelected = listFindNoCase(selectedSeats, seatID) GT 0;
// Determine seat style
if (isReserved) {
seatStyle = "background: ##f44336; color: white; cursor: not-allowed;";
seatIcon = "✗";
} else if (isSelected) {
seatStyle = "background: ##4caf50; color: white; cursor: pointer;";
seatIcon = "✓";
} else {
seatStyle = "background: ##2196f3; color: white; cursor: pointer;";
seatIcon = "○";
}
// Add hover effect for available seats
if (NOT isReserved) {
seatStyle &= " border: 2px solid transparent;";
}
</cfscript>
<cfoutput>
<td style="padding: 0;">
<cfif isReserved>
<div style="#seatStyle# width: 40px; height: 40px; line-height: 40px; text-align: center; border-radius: 5px; font-size: 20px;" title="Reserved: #seatID#">
#seatIcon#
</div>
<cfelse>
<button
type="button"
onclick="toggleSeat('#seatID#')"
style="#seatStyle# width: 40px; height: 40px; border: none; border-radius: 5px; font-size: 20px;"
title="Seat #seatID# - $#seatPrice#"
onmouseover="this.style.borderColor='##ff9800'"
onmouseout="this.style.borderColor='transparent'">
#seatIcon#
</button>
</cfif>
</td>
</cfoutput>
</cfloop>
</tr>
</cfloop>
</tbody>
</table>
</div>
<!--- Hidden field to track selections --->
<input type="hidden" name="selectedSeats" id="selectedSeats" value="<cfoutput>#selectedSeats#</cfoutput>">
</form>
<!--- JavaScript for seat selection --->
<script>
function toggleSeat(seatID) {
var selectedField = document.getElementById('selectedSeats');
var selectedSeats = selectedField.value;
var seatList = selectedSeats ? selectedSeats.split(',') : [];
var index = seatList.indexOf(seatID);
if (index > -1) {
// Remove seat
seatList.splice(index, 1);
} else {
// Add seat
seatList.push(seatID);
}
selectedField.value = seatList.join(',');
// Reload page to show selection
document.forms[0].submit();
}
</script>
<!--- Legend --->
<div style="display: flex; justify-content: center; gap: 30px; margin: 20px 0; padding: 20px; background: white; border-radius: 5px;">
<div style="display: flex; align-items: center;">
<div style="width: 30px; height: 30px; background: ##2196f3; border-radius: 5px; margin-right: 10px;"></div>
<span>Available</span>
</div>
<div style="display: flex; align-items: center;">
<div style="width: 30px; height: 30px; background: ##4caf50; border-radius: 5px; margin-right: 10px;"></div>
<span>Selected</span>
</div>
<div style="display: flex; align-items: center;">
<div style="width: 30px; height: 30px; background: ##f44336; border-radius: 5px; margin-right: 10px;"></div>
<span>Reserved</span>
</div>
</div>
<!--- Selection Summary --->
<cfif len(trim(selectedSeats)) GT 0>
<div style="background: ##4caf50; color: white; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h3 style="margin: 0 0 10px 0;">Your Selection</h3>
<cfset selectedList = listToArray(selectedSeats)>
<cfset totalCost = 0>
<table style="width: 100%; color: white;">
<thead>
<tr style="border-bottom: 2px solid white;">
<th style="padding: 10px; text-align: left;">Seat</th>
<th style="padding: 10px; text-align: left;">Row</th>
<th style="padding: 10px; text-align: right;">Price</th>
</tr>
</thead>
<tbody>
<cfloop array="#selectedList#" index="seat">
<cfset seatRow = left(seat, 1)>
<cfset rowNum = arrayFind(rowLetters, seatRow)>
<cfset price = getSeatPrice(rowNum)>
<cfset totalCost += price>
<cfoutput>
<tr>
<td style="padding: 10px; font-weight: bold;">#seat#</td>
<td style="padding: 10px;">Row #seatRow#</td>
<td style="padding: 10px; text-align: right;">$#price#</td>
</tr>
</cfoutput>
</cfloop>
<tr style="border-top: 2px solid white; font-size: 18px; font-weight: bold;">
<td colspan="2" style="padding: 10px;">TOTAL</td>
<td style="padding: 10px; text-align: right;"><cfoutput>$#totalCost#</cfoutput></td>
</tr>
</tbody>
</table>
<div style="text-align: center; margin-top: 20px;">
<button type="button" style="padding: 15px 40px; background: white; color: ##4caf50; border: none; border-radius: 5px; font-size: 16px; font-weight: bold; cursor: pointer;">
Proceed to Checkout
</button>
</div>
</div>
</cfif>
<!--- Pricing Table --->
<div style="background: white; border: 1px solid ##ddd; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h3>Seating & Pricing</h3>
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background: ##2196f3; color: white;">
<th style="padding: 12px; border: 1px solid ##ddd; text-align: left;">Section</th>
<th style="padding: 12px; border: 1px solid ##ddd; text-align: left;">Rows</th>
<th style="padding: 12px; border: 1px solid ##ddd; text-align: right;">Price</th>
<th style="padding: 12px; border: 1px solid ##ddd; text-align: center;">Seats Available</th>
</tr>
</thead>
<tbody>
<tr>
<td style="padding: 12px; border: 1px solid ##ddd;"><strong>Premium</strong></td>
<td style="padding: 12px; border: 1px solid ##ddd;">A - B</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: right;">$50</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: center;">
<cfset premiumAvailable = 20 - listLen(listFilter(reservedSeats, function(seat) { return left(seat, 1) EQ "A" OR left(seat, 1) EQ "B"; }))>
<cfoutput>#premiumAvailable# / 20</cfoutput>
</td>
</tr>
<tr>
<td style="padding: 12px; border: 1px solid ##ddd;"><strong>Standard</strong></td>
<td style="padding: 12px; border: 1px solid ##ddd;">C - E</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: right;">$35</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: center;">27 / 30</td>
</tr>
<tr>
<td style="padding: 12px; border: 1px solid ##ddd;"><strong>Economy</strong></td>
<td style="padding: 12px; border: 1px solid ##ddd;">F - H</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: right;">$25</td>
<td style="padding: 12px; border: 1px solid ##ddd; text-align: center;">29 / 30</td>
</tr>
</tbody>
</table>
</div>
<!--- Example: Airline Seating Layout --->
<div style="margin: 40px 0;">
<h3>Example 2: Airline Seating Layout (3-3 Configuration)</h3>
<div style="background: white; border: 1px solid ##ddd; padding: 20px; border-radius: 5px;">
<cfscript>
airlineRows = 10;
leftSeats = 3; // ABC
rightSeats = 3; // DEF
</cfscript>
<table style="margin: 0 auto; border-collapse: separate; border-spacing: 3px;">
<!--- OUTER LOOP: Rows --->
<cfloop index="row" from="1" to="#airlineRows#">
<tr>
<!--- Row Number --->
<cfoutput>
<td style="padding: 5px; font-weight: bold; color: ##666;">#row#</td>
</cfoutput>
<!--- LEFT SIDE: Seats A, B, C --->
<cfloop index="seat" from="1" to="#leftSeats#">
<cfset seatLetter = chr(64 + seat)> <!--- A, B, C --->
<cfoutput>
<td style="padding: 0;">
<div style="width: 30px; height: 30px; line-height: 30px; text-align: center; background: ##2196f3; color: white; border-radius: 3px; font-size: 11px;" title="#row##seatLetter#">
#seatLetter#
</div>
</td>
</cfoutput>
</cfloop>
<!--- AISLE --->
<td style="width: 30px;"></td>
<!--- RIGHT SIDE: Seats D, E, F --->
<cfloop index="seat" from="4" to="6">
<cfset seatLetter = chr(64 + seat)> <!--- D, E, F --->
<cfoutput>
<td style="padding: 0;">
<div style="width: 30px; height: 30px; line-height: 30px; text-align: center; background: ##2196f3; color: white; border-radius: 3px; font-size: 11px;" title="#row##seatLetter#">
#seatLetter#
</div>
</td>
</cfoutput>
</cfloop>
</tr>
</cfloop>
</table>
<p style="text-align: center; margin-top: 20px; color: ##666;">
<strong>Configuration:</strong> 3-3 (60 total seats)
</p>
</div>
</div>
