Adobe ColdFusion 8

ArrayAvg

Description

Calculates the average of the values in an array.

Returns

Number. If the array parameter value is an empty array, returns zero.

Category

Array functions, Mathematical functions

Function syntax

ArrayAvg(array)

See also

ArraySum; "Basic array techniques" in the ColdFusion Developer's Guide

Parameters

Parameter

Description

array

Name of an array

Usage

The following example uses the ColdFusion built-in variable Form.fieldNames, which is available on the action page of a form. It contains a comma-delimited list of the names of the fields on the form.

Example

<!--- This example shows the use of ArrayAvg. --->
<!-- The following lines of code keep track of the form fields that can 
be dynamically generated on the screen. It uses the Fieldnames variable
with the ListLen function to determine the number of fields on the form. --->
<cfset FormElem = 2>
    <cfif Isdefined("Form.Submit")>
        <cfif Form.Submit is "More">
            <cfset FormElem = ListLen(Form.Fieldnames)>
        </cfif>
    </cfif>

<html>
<head>
<title>ArrayAvg Example</title>
</head>
<body>
<h3>ArrayAvg Example</h3>
<p> This example uses ArrayAvg to find the average of the numbers that you enter
    into an array.<br> 
To enter more than two numbers click the <b>more</b> button.
</p>
<form action = "arrayavg.cfm">
<!--- The following code initially creates two fields. It adds fields if the
    user presses MORE. FormElem is initialized to two at the beginning of this
    code to show that the form has two fields. ----->
<input type = "submit" name = "submit" value = "more">
<table cellspacing = "2" cellpadding = "2" border = "0">
<cfloop index = "LoopItem" from = "1" to = "#FormElem#">
    <tr>
        <cfoutput>
        <th align = "left">Number #LoopItem#</th>
        <td><input type = "text" name = "number#LoopItem#"></td>
        </cfoutput>
    </tr>
</cfloop>
</table>
<input type = "submit" name = "submit" value = "get the average">
</form>

<!--- Create an array. --->
<cfif IsDefined("FORM.submit")>
    <cfset myNumberArray = ArrayNew(1)>
    <cfset Count = 1>
    <cfloop index = "ListItem" list = "#Form.Fieldnames#">
         <cfif Left(ListItem,3) is "Num">
            <cfset myNumberArray[Count] = Val("number#Count#")>
            <cfset count = IncrementValue(Count)>
        </cfif> 
    </cfloop>
        
    <cfif Form.Submit is "get the average">    
        <!--- use ArrayAvg to get the average of the two numbers --->
        <p>The average of the numbers that you entered is
        <cfoutput>#ArrayAvg(myNumberArray)#.</cfoutput>
    <cfelse>
        <cfoutput>Try again. You must enter at least two numeric values.
        </cfoutput>
    </cfif>    
</cfif>    
</body>
</html>