KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility to set elements in an array at specified index
PRODUCT: 4D | VERSION: 15.x | PLATFORM: Mac & Win
Published On: March 30, 2017

Utility to insert a value into an array at a specified index. If the index exceeds the length of the array, empty elements are added.

// Method: UTIL_SET_ARR_ELEM_VAL
// Set value in array at specified index. If index exceeds size of array, insert
// empty elements in between.

// $1 - Pointer to array
// $2 - Index
// $3 - Pointer to value to set

C_POINTER($arrPtr;$1;$valPtr;$3)
C_LONGINT($indx;$2)
$arrPtr:=$1
$indx:=$2

$size:=Size of array($arrPtr->)
If ($indx>$size)
   INSERT IN ARRAY($arrPtr->;$size+1;$indx-$size)
End if

If (Count parameters>=3)
   $valPtr:=$3
   $arrPtr->{$indx}:=$valPtr->
End if


Example:

User wants to insert a value into the 2nd element of an array:
C_TEXT($valueToSet)
ARRAY TEXT($arr;0)
$valueToSet:="element2"
UTIL_SET_ARR_ELEM_VAL (->$arr;2;->$valueToSet)

The result of $arr are: