Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active March 1, 2021 21:02
Show Gist options
  • Save JamoCA/9bac4917179a3e44a542bc4768a95a31 to your computer and use it in GitHub Desktop.
Save JamoCA/9bac4917179a3e44a542bc4768a95a31 to your computer and use it in GitHub Desktop.
ArrayFirstDefined: Returns first "defined" array item (ColdFusion cfml)
<cfscript>
/* 20210301 ArrayFirstDefined: Returns first "defined" array item
TryCF: https://www.trycf.com/gist/9bac4917179a3e44a542bc4768a95a31
Twitter: https://twitter.com/gamesover/status/1366439036903120897
ACF: Requires CF2018+ to use arrayFirst().
Lucee CFML: Reproted arrayFirst() bug. https://luceeserver.atlassian.net/browse/LDEV-3319 */
any function arrayFirstDefined(required array array, any fallbackValue="") output=false hint="Returns first defined array item" {
for (local.item in arguments.array){
if (not isNull(local.item)) return local.item;
}
return arguments.fallbackValue;
}
/* Test */
a = [];
arrayResize(a, 15);
a[15]=1;
results = [
"arrayLen" = arrayLen(a),
"arrayFirst" = arrayFirst(a),
"arrayFirstDefined" = arrayFirstDefined(a),
"originalArray" = a
];
writedump(var=results, label="Test Results");
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment