Whatever message this page gives is out now! Go check it out!

ArrayAppend

Last update:
May 18, 2026

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

ArrayPrependAdding 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

ParameterDescription
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]
Example 2
<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
Example 3
<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>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page