StructKeyExists()

edit

Determines whether a specific key is present in a structure.

In CFML, by default, this will return false for any keys with a null value, however, if Full Null Support is enabled, it will return true.

Null Handling in CFML

See Also: Elvis and Safe Navigation Operators

For many common use cases, consider using these more concise alternatives:

  • Elvis operator (?:) - Returns a default value if the left side is null or undefined:

    // Instead of:
    if ( structKeyExists( args, "name" ) ) {
        result = args.name;
    } else {
        result = "default";
    }
    // Use:
    result = args.name ?: "default";
    
  • Safe navigation operator (?.) - Safely traverse nested properties, combine with elvis for a default value:

    // Instead of:
    if ( structKeyExists( user, "address" ) && structKeyExists( user.address, "city" ) ) {
        city = user.address.city;
    } else {
        city = "Unknown";
    }
    // Use:
    city = user?.address?.city ?: "Unknown";
    

    Operators

StructKeyExists( struct=struct, key=string );

Returns: Boolean

Argument Description
struct
struct, required
edit

Name of structure to test

Alias: structure, object

key
string, required
edit

Key to test

Usage Notes

edit

Using this function to check if a session variable exists, will create a session, if it doesn't already exist.

With Lucee 6.2, we have introduced SessionExists() which can be safely used to check if a session has been created

Examples

edit

Non-Member Function

animals = {
	cow: "moo",
	pig: "oink",
	cat: "meow",
	bird: "chirp"
};

// Check to see if key exists in struct if ( StructKeyExists(animals, "snail") ) { echo("There is a snail in 'animals'"); } else { echo("No snail exists in 'animals'"); }

See also