Copy and compare arrays

An array can be copy to another one, same as variables:

   aColors2 :=  aColors

But be careful; aColors2 doesn’t another copy of aColors; it’s simply another variable to indicate same array.  Because an array identifier doesn’t array itself, it’s only a reference (pointer) for access that array. Look at this :

   aColors2[ 3 ] :=  "magenta"
   ? aColors[ 3 ]     // magenta, not red

Because aColors2 and  aColors are exactly same array.

Another way for duplicate an array may be ACOPY() function:

  aColors3 := ARRAY( LEN( aColors ) )
  ACOPY( aColors, aColors3 )

Syntax :

 ACOPY(<aSource>, <aTarget>, [<nStart>], [<nCount>], [<nTargetPos>]) 
      --> aTarget

ACOPY() is an array function that copies elements from the <aSource> array to the <aTarget> array.  The <aTarget> array must already exist and be large enough to hold the copied elements.  If the aSource> array has more elements, some elements will not be copied.

ACOPY() copies values of all data types including NIL and code blocks.

If an element of the <aSource> array is a sub-array, the corresponding element in the <aTarget> array will contain a reference to the subarray. Thus, ACOPY() will not create a complete duplicate of a multidimensional array.  To do this, use the ACLONE() function

Syntax :

      ACLONE(<aSource>) --> aDuplicate

ACLONE() is an array function that creates a complete duplicate of the  <aSource> array.  If <aSource> contains subarrays, ACLONE() creates  matching subarrays and fills them with copies of the values in the  <aSource> subarrays.  ACLONE() is similar to ACOPY(), but ACOPY() does  not duplicate nested arrays.

 aColors4 :=  ACLONE( aColors )
 aColors4[ 3 ] :=  "magenta"
 ? aColors[ 3 ]     // red

Thus, simply assign an array to another may cause misunderstanding.


The “==” operator ( not “=” ) can be used for comparing two arrays. This usage too require a bit attention:  When  compare two array with conjunction “==” operator, result will be .T. ( true ) only if both array are the same:

  aColors2 :=  aColors
  ? aColors2 ==  aColors  // .T.
  aColors3 :=  ACOPY( aColors )
  ? aColors3 ==  aColors  // .F.
  aColors4 :=  ACLONE( aColors )
  ? aColors4 ==  aColors  // .F.

For a “hand-made” array compare function see source ( .prg ) file.