array_map_op

The `array_map_op` directive applies a specific operation to each element of an array-type variable in NGINX configuration.

Syntaxarray_map_op operation $array_var [to=$target_variable];
Defaultnone
Contexthttp, server, location, if in server, if in location
Arguments2-3

Description

The array_map_op directive is utilized in NGINX to perform operations on every element within an array-typed variable, which is a feature provided by the array-var-nginx-module. It takes two or three arguments depending on the context and serves to manipulate the elements of an array according to a specified template or function. The first argument defines the operation to be applied, while the second argument specifies the array variable involved. If a third argument is provided, it can indicate additional options for the operation such as whether the operation should modify the array in place.

When you use array_map_op, NGINX works under the hood to iterate through each item of the specified array and applies the defined operation, storing the result back in the same array or a new one as dictated by the configuration. This directive is especially useful for cases where you need to transform the data in an array before further processing, such as generating SQL conditions from an array of field names. Using the directive in combination with array_split and array_join allows for powerful manipulations of query strings or other data formats within NGINX without involving external scripting languages.

Config Example

location /example {
    array_split "," $arg_query to=$array;
    array_map_op trim_spaces $array;
    array_join ' AND ' $array to=$where_clause;
    echo "SELECT * FROM my_table WHERE $where_clause";
}

Ensure that the operation specified as the first argument is valid and appropriately defined to avoid configuration errors.

Attempting to use an undefined array variable will lead to unexpected results or errors at runtime.

Be aware of the in-place modification option as it may alter the original array without creating a new instance, depending on the use case.

← Back to all directives