Multiply an array by a number
I am trying to multiply each element of an array by a number (5)
Is there an easy way to do it or need to write a function for that?
I am trying to multiply each element of an array by a number (5)
Is there an easy way to do it or need to write a function for that?
As for a function..
<cffunction
access="public"
returntype="array"
name="multiplyBy"
output="false">
<!--- Arguments. --->
<cfargument
required="true"
type="array"
name="myArray" />
<cfargument
required="false"
type="numeric"
name="multiplier"
default="5" />
<!--- Local variables. --->
<cfset local.i = 0 />
<cfset local.return = arrayNew( 1 ) />
<!--- Iterate over provided loop and append result into return variable. --->
<cfloop array="#arguments.myArray#" index="local.i">
<cfset arrayAppend( local.return, ( local.i * arguments.multiplier ) ) />
</cfloop>
<!--- Return. --->
<cfreturn local.return />
</cffunction>
<!--- Create a test array of data. --->
<cfset testArray = [ 5, 10, 15, 20 ] />
<!--- When no multiplier argument is provided, default multiplies by 5. --->
<cfdump var="#multiplyBy( testArray )#" />
<hr>
<!--- When a multiplier is provided, it is used in the calculations. --->
<cfdump var="#multiplyBy( testArray, 12 )#" />
Already have an account? Login
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.