- 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
Appends an array element to an array. Concatenates arrays when the merge argument is set to true and the value argument is an array.
Returns
True, on successful completion.
Category
Function syntax
ArrayAppend(array, value [,merge])
See also
ArrayPrepend; Adding elements to an array in Basic array techniques in the Developing ColdFusion Applications
History
Coldfusion 10: Added the merge argument
ColdFusion MX: Changed behavior: this function can be used on XML objects.
Parameters
Parameter |
Description |
|---|---|
array |
Name of an array |
value |
Value to add at end of array |
merge |
If set to true, and value parameter is an array, appends array elements individually to the source array. If false (default) the complete array is added as one element at the end, in the source array. If value is not an array this argument is ignored. |
Example 1
<cfscript>
myArray=[1,2,3,4,5];
ArrayAppend(myArray,6,"true");
writeoutput(serializeJSON(myArray)); //adds the value 6 to myArray
</cfscript>
Output
[1,2,3,4,5,6]
<cfscript>
myArray=[1,2,3,4,5];
ArrayAppend(myArray,[8,9],"false"); // merge=false
writedump(myArray) //adds the new array as a single element
</cfscript>
Output
<cfscript>
myArray=[1,2,3,4,5];
ArrayAppend(myArray,[8,9],"true"); // merge=true
writedump(myArray) //adds the new array elements as individual elements
</cfscript>
Output
Real-world use cases of using the ArrayAppend function
eCommerce shopping cart management
An online store where customers add items to their shopping cart dynamically. eCommerce sites need dynamic cart management where customers add items individually, and sometimes bulk-add from wishlists or saved collections.
<cfscript>
// Initialize empty shopping cart
shoppingCart = [];
// Customer browsing and adding products
function addProductToCart(cart, productId, productName, price, quantity) {
// Create product object
product = {
id: productId,
name: productName,
price: price,
quantity: quantity,
addedDate: now(),
subtotal: price * quantity
};
// Append single product to cart
ArrayAppend(cart, product);
writeOutput("<p>✅ Added to cart: " & productName & " (Qty: " & quantity & ") - $" &
numberFormat(product.subtotal, "999.99") & "</p>");
return true;
}
// Customer adds items one by one
writeOutput("<h2>Shopping Cart Demo</h2>");
writeOutput("<h3>Adding Items to Cart:</h3>");
addProductToCart(shoppingCart, 1001, "Wireless Headphones", 79.99, 1);
addProductToCart(shoppingCart, 1002, "USB Cable", 12.99, 2);
addProductToCart(shoppingCart, 1003, "Phone Case", 24.99, 1);
// Display current cart contents
writeOutput("<h3>Current Cart Contents:</h3>");
writeOutput("<table border='1' cellpadding='5'>");
writeOutput("<tr><th>Product</th><th>Price</th><th>Qty</th><th>Subtotal</th></tr>");
cartTotal = 0;
for (item in shoppingCart) {
writeOutput("<tr>");
writeOutput("<td>" & item.name & "</td>");
writeOutput("<td>$" & numberFormat(item.price, "99.99") & "</td>");
writeOutput("<td>" & item.quantity & "</td>");
writeOutput("<td>$" & numberFormat(item.subtotal, "99.99") & "</td>");
writeOutput("</tr>");
cartTotal += item.subtotal;
}
//writeOutput("<tr style='background-color: #f0f0f0; font-weight: bold;'>");
writeOutput("<td colspan='3'>TOTAL</td>");
writeOutput("<td>$" & numberFormat(cartTotal, "999.99") & "</td>");
writeOutput("</tr>");
writeOutput("</table>");
// Bulk add from wishlist (demonstrating merge functionality)
writeOutput("<h3>Adding Items from Wishlist:</h3>");
wishlistItems = [
{id: 2001, name: "Bluetooth Speaker", price: 49.99, quantity: 1, addedDate: now(), subtotal: 49.99},
{id: 2002, name: "Screen Protector", price: 9.99, quantity: 3, addedDate: now(), subtotal: 29.97}
];
// Merge wishlist items into cart (merge=true to add individual elements)
ArrayAppend(shoppingCart, wishlistItems, true);
writeOutput("<p>✅ Added " & arrayLen(wishlistItems) & " items from wishlist</p>");
writeOutput("<p><strong>Updated cart size:</strong> " & arrayLen(shoppingCart) & " items</p>");
</cfscript>
Log file processing and error tracking
An application monitoring system collecting and categorizing log entries. Log processing systems need to dynamically collect entries, categorize them, and merge logs from multiple sources for comprehensive monitoring.
<cfscript>
// Initialize log collection arrays
errorLogs = [];
warningLogs = [];
infoLogs = [];
allLogs = [];
// Function to process incoming log entries
function logMessage(level, message, component, userId) {
timestamp = now();
logEntry = {
timestamp: timestamp,
level: level,
message: message,
component: component,
userId: userId,
sessionId: createUUID()
};
// Add to appropriate category array
switch (level) {
case "ERROR":
ArrayAppend(errorLogs, logEntry);
break;
case "WARNING":
ArrayAppend(warningLogs, logEntry);
break;
case "INFO":
ArrayAppend(infoLogs, logEntry);
break;
}
// Also add to master log array
ArrayAppend(allLogs, logEntry);
return logEntry;
}
writeOutput("<h2>Application Log Processing System</h2>");
// Simulate incoming log messages
writeOutput("<h3>Processing Log Entries:</h3>");
logMessage("ERROR", "Database connection failed", "DatabaseService", "admin");
logMessage("WARNING", "High memory usage detected", "SystemMonitor", "system");
logMessage("INFO", "User login successful", "AuthService", "user123");
logMessage("ERROR", "File not found: config.xml", "ConfigLoader", "admin");
logMessage("WARNING", "API rate limit approaching", "APIGateway", "user456");
logMessage("INFO", "Backup completed successfully", "BackupService", "system");
// Display categorized logs
writeOutput("<h3>Log Summary:</h3>");
writeOutput("<div style='display: flex; gap: 20px;'>");
// Error logs
// writeOutput("<div style='border: 1px solid red; padding: 10px; background-color: #ffe6e6;'>");
writeOutput("<h4 style='color: red;'>🚨 Errors (" & arrayLen(errorLogs) & ")</h4>");
for (log in errorLogs) {
writeOutput("<p><small>" & timeFormat(log.timestamp, "HH:mm:ss") & "</small><br>");
writeOutput("<strong>" & log.component & ":</strong> " & log.message & "</p>");
}
writeOutput("</div>");
// Warning logs
//writeOutput("<div style='border: 1px solid orange; padding: 10px; background-color: #fff3cd;'>");
writeOutput("<h4 style='color: orange;'>⚠️ Warnings (" & arrayLen(warningLogs) & ")</h4>");
for (log in warningLogs) {
writeOutput("<p><small>" & timeFormat(log.timestamp, "HH:mm:ss") & "</small><br>");
writeOutput("<strong>" & log.component & ":</strong> " & log.message & "</p>");
}
writeOutput("</div>");
// Info logs
//writeOutput("<div style='border: 1px solid blue; padding: 10px; background-color: #e6f3ff;'>");
writeOutput("<h4 style='color: blue;'>ℹ️ Info (" & arrayLen(infoLogs) & ")</h4>");
for (log in infoLogs) {
writeOutput("<p><small>" & timeFormat(log.timestamp, "HH:mm:ss") & "</small><br>");
writeOutput("<strong>" & log.component & ":</strong> " & log.message & "</p>");
}
writeOutput("</div>");
writeOutput("</div>");
// Batch processing simulation - merge logs from different servers
writeOutput("<h3>Merging Logs from Multiple Servers:</h3>");
server1Logs = [
{timestamp: now(), level: "ERROR", message: "Server overloaded", component: "LoadBalancer", userId: "system"},
{timestamp: now(), level: "INFO", message: "Cache cleared", component: "CacheService", userId: "admin"}
];
server2Logs = [
{timestamp: now(), level: "WARNING", message: "Disk space low", component: "FileSystem", userId: "system"},
{timestamp: now(), level: "INFO", message: "Scheduled task completed", component: "TaskScheduler", userId: "system"}
];
// Merge all server logs into master array (merge=true for individual elements)
writeOutput("<p>Merging logs from Server 1 (" & arrayLen(server1Logs) & " entries)...</p>");
ArrayAppend(allLogs, server1Logs, true);
writeOutput("<p>Merging logs from Server 2 (" & arrayLen(server2Logs) & " entries)...</p>");
ArrayAppend(allLogs, server2Logs, true);
writeOutput("<p><strong>Total log entries:</strong> " & arrayLen(allLogs) & "</p>");
// Generate summary report
logStats = {ERROR: 0, WARNING: 0, INFO: 0};
for (log in allLogs) {
logStats[log.level]++;
}
writeOutput("<h4>Final Statistics:</h4>");
writeOutput("<ul>");
writeOutput("<li><strong>Errors:</strong> " & logStats.ERROR & "</li>");
writeOutput("<li><strong>Warnings:</strong> " & logStats.WARNING & "</li>");
writeOutput("<li><strong>Info:</strong> " & logStats.INFO & "</li>");
writeOutput("</ul>");
</cfscript>
Survey response collection system
An online survey platform collecting and aggregating responses from multiple participants. Survey platforms need to collect responses individually and in batches, categorize different response types, and merge data from multiple sources for comprehensive analysis.
<cfscript>
// Survey structure
survey = {
title: "Customer Satisfaction Survey 2024",
questions: [
{id: 1, text: "How satisfied are you with our service?", type: "rating"},
{id: 2, text: "What features would you like to see improved?", type: "multiple_choice"},
{id: 3, text: "Additional comments", type: "text"}
]
};
// Initialize response collection
allResponses = [];
ratingResponses = [];
textComments = [];
function submitSurveyResponse(respondentId, responses) {
surveyResponse = {
respondentId: respondentId,
submitDate: now(),
responses: responses,
completionTime: randRange(2, 15) // minutes (simulated)
};
// Add to main responses array
ArrayAppend(allResponses, surveyResponse);
// Extract and categorize specific response types
for (response in responses) {
if (response.questionId == 1) {
// Rating question - collect for analysis
ArrayAppend(ratingResponses, {
respondentId: respondentId,
rating: response.value,
submitDate: surveyResponse.submitDate
});
}
if (response.questionId == 3 && response.value != "") {
// Text comments - collect for review
ArrayAppend(textComments, {
respondentId: respondentId,
comment: response.value,
submitDate: surveyResponse.submitDate
});
}
}
return surveyResponse;
}
writeOutput("<h2>Survey Response Collection Demo</h2>");
writeOutput("<h3>" & survey.title & "</h3>");
// Simulate survey responses
writeOutput("<h3>Collecting Survey Responses:</h3>");
// Response 1
response1 = [
{questionId: 1, value: 5},
{questionId: 2, value: "Mobile app"},
{questionId: 3, value: "Great service, keep it up!"}
];
submitSurveyResponse("RESP001", response1);
writeOutput("<p>✅ Response from RESP001 collected</p>");
// Response 2
response2 = [
{questionId: 1, value: 4},
{questionId: 2, value: "Website speed"},
{questionId: 3, value: ""}
];
submitSurveyResponse("RESP002", response2);
writeOutput("<p>✅ Response from RESP002 collected</p>");
// Response 3
response3 = [
{questionId: 1, value: 3},
{questionId: 2, value: "Customer support"},
{questionId: 3, value: "Response time could be better"}
];
submitSurveyResponse("RESP003", response3);
writeOutput("<p>✅ Response from RESP003 collected</p>");
// Batch import responses from external survey tool
writeOutput("<h3>Batch Import from External Survey Tool:</h3>");
externalResponses = [
{
respondentId: "EXT001",
submitDate: now(),
responses: [{questionId: 1, value: 5}, {questionId: 2, value: "Mobile app"}, {questionId: 3, value: "Excellent!"}],
completionTime: 8
},
{
respondentId: "EXT002",
submitDate: now(),
responses: [{questionId: 1, value: 2}, {questionId: 2, value: "All features"}, {questionId: 3, value: "Needs major improvements"}],
completionTime: 12
}
];
// Merge external responses (merge=true to add individual responses)
ArrayAppend(allResponses, externalResponses, true);
writeOutput("<p>✅ Imported " & arrayLen(externalResponses) & " responses from external system</p>");
// Process external responses for categorization
for (extResponse in externalResponses) {
for (response in extResponse.responses) {
if (response.questionId == 1) {
ArrayAppend(ratingResponses, {
respondentId: extResponse.respondentId,
rating: response.value,
submitDate: extResponse.submitDate
});
}
if (response.questionId == 3 && response.value != "") {
ArrayAppend(textComments, {
respondentId: extResponse.respondentId,
comment: response.value,
submitDate: extResponse.submitDate
});
}
}
}
// Generate analysis
writeOutput("<h3>Survey Analysis:</h3>");
// writeOutput("<div style='background-color: #f0f8ff; padding: 15px; border: 1px solid #ccc;'>");
writeOutput("<h4>📊 Response Summary</h4>");
writeOutput("<p><strong>Total Responses:</strong> " & arrayLen(allResponses) & "</p>");
writeOutput("<p><strong>Rating Responses:</strong> " & arrayLen(ratingResponses) & "</p>");
writeOutput("<p><strong>Text Comments:</strong> " & arrayLen(textComments) & "</p>");
// Calculate average rating
if (arrayLen(ratingResponses) > 0) {
totalRating = 0;
for (rating in ratingResponses) {
totalRating += rating.rating;
}
avgRating = totalRating / arrayLen(ratingResponses);
writeOutput("<p><strong>Average Rating:</strong> " & numberFormat(avgRating, "9.9") & "/5.0</p>");
}
writeOutput("</div>");
// Display recent comments
writeOutput("<h4>Recent Comments:</h4>");
//writeOutput("<div style='max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px;'>");
for (comment in textComments) {
//writeOutput("<div style='margin-bottom: 10px; padding: 8px; background-color: #f9f9f9;'>");
writeOutput("<strong>" & comment.respondentId & "</strong> (" &
dateFormat(comment.submitDate, "mm/dd/yyyy") & "):<br>");
writeOutput("</div>");
}
writeOutput("</div>");
// Response distribution
writeOutput("<h4>Rating Distribution:</h4>");
ratingDist = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0};
for (rating in ratingResponses) {
ratingDist[rating.rating]++;
}
writeOutput("<table border='1' cellpadding='5'>");
writeOutput("<tr><th>Rating</th><th>Count</th><th>Percentage</th></tr>");
for (i = 1; i <= 5; i++) {
percentage = arrayLen(ratingResponses) > 0 ? (ratingDist[i] / arrayLen(ratingResponses)) * 100 : 0;
writeOutput("<tr>");
writeOutput("<td>" & i & " stars</td>");
writeOutput("<td>" & ratingDist[i] & "</td>");
writeOutput("<td>" & numberFormat(percentage, "99.9") & "%</td>");
writeOutput("</tr>");
}
writeOutput("</table>");
</cfscript>
