/
How to work with arrays

How to work with arrays

This section combines core array concepts to demonstrate practical use cases and examples.

Array creation

Any variable type can be transformed into an array by adding the array symbols [] after the type declaration.f

Example 1 - Empty array declaration

string [] fruit;

Creates an uninitialized array with no elements. The array exists but contains no values.

Example 2 - Array with predefined values

string [] fruit = {"Apple", "Apricot", "Banana", "Cherry"};

Initializes an array with a fixed set of values, specifying the elements directly during declaration.

Example 3 - Array from delimited string

string [] produce = "Apple|Apricot|Avocado|Banana|Blackberry|Blueberry|Cherry|Coconut";

Leverages the language's automatic conversion of pipe-delimited strings into an array. This method provides a concise way to create arrays from text-based lists.


Array keys

Using a key-value pair lets you create key-value lists (maps) and retrieve values from them by using a string inside the operator (instead of a number).

Example 1 - Add values by key

string [] fruitColor; fruitColor["Apple"] = "Red"; fruitColor["Banana"] = "Yellow"; fruitColor["Orange"] = "Orange";

Creates an associative array where each fruit is a key linked to its corresponding color. This approach creates flexible, named collections where elements can be accessed by meaningful identifiers instead of numeric indexes.

Example 2 - Retrieve values by key

return fruitColor["Banana"];

Retrieves the value associated with a specific key. In this example, it would return "Yellow". This method provides direct, readable access to stored values using their unique identifiers.

 


Array values

Any variable type can be transformed into an array by adding the array symbols [] after the type declaration.

Example 1 - Add values by a specific index

string [] fruit; fruit[0] = "Apple"; fruit[1] = "Apricot"; fruit[3] = "Banana";

Directly assigns values to specific array positions using numeric indexes. This method allows precise control over element placement, with the ability to leave gaps between assigned values. Note that unassigned indexes may remain undefined.

Example 2 - Add values dynamically

string [] fruit; fruit += "Apple"; fruit += "Apricot"; fruit += "Banana";

Adds elements to the end of the array sequentially. This approach automatically manages array expansion, appending each new value to the next available position without manually tracking indexes.

Example 3 - Retrieve a specific value

return fruit[1];

Accesses a specific array element using its numeric index. This example would return "Apricot,” the second element in the array (remembering that array indexing typically starts at 0).

 

 

 

Related content