Mikrotik Scripting – Array Push Function

Since the scripting language at the moment on Router OS version 6.13 is lacking in the array editing department, here is a simple array push function I created.

# Usage: [$arrayPush <$array name> <value> <key position to place value (0-n or -1)>]
# Input an array name, value, and the key position to push the value to. To push value to the end of the array, enter -1.
# If array doesn't already exist, you must declare the variable and set it to "" before calling the function.

:global arrayPush do={
    :if ($2="") do={ :error "You did not specify a value to add to the array."; }
    :if ($1!="" && $3="") do={ :error "You did not specify the key position to place the value in the array."; }
    :if (($3<(-1)) || (([:typeof $3]!="num") && ([:typeof $3]!="str")) || ($3>([:len $1]-1))) do={ :error "Argument 2 invalid."; }
    :local string;
    :if ([:typeof $1]="array" && $3=(-1)) do={
        :foreach item in=$1 do={ :set string ($string . "," . $item); }
        :set string ($string . "," . $2);
        :set string [:toarray $string];
        :return $string;
    } 
    :if ([:typeof $1]="array" && [:len $1]>="0") do={
        :local counter "0";
        :foreach item in=$1 do={ 
            :if ($counter!=[:tonum $3]) do={ 
                :set string ($string . "," . $item);
                :set counter ($counter+1);
            } else={ 
                :set string ($string . "," . $2); 
                :set string ($string . "," . $item); 
                :set counter ($counter+1); 
            }
        }
        :set string [:toarray $string];        
        :return $string;
    } 
    :if ($1="") do={
        :set string $2;
        :set string [:toarray $string];
        :return $string;
    }
}

Leave a Reply