Declare an array

From CodeCodex

Implementations[edit]

Java[edit]

One dimension[edit]

 String[] oneDimension;

or

 String oneDimension[];

Populating an array with values upon declaration:

 String[] oneDimension = { "a","b","c" };

Declaring and creating an array of a set size:

 String[] oneDimension = new String[10];
 int[] oneDimension = new int[1000];

Two dimension[edit]

 String[][] twoDimension;

or

 String[] twoDimension[];

or

 String twoDimension[][];

Populating an array with values upon declaration:

 String[][] twoDimension = { {"1","2","3"}, {"4","5","6"}, {"7","8","9"} };

Common Lisp[edit]

* #(1 2 3)

#(1 2 3)


* #2A((1 2) (3 4))

#2A((1 2) (3 4))

OCaml[edit]

No need for type declarations in OCaml, thanks to type inference. OCaml has homogeneous arrays and provides array literals. For example:

# [|1; 2; 3|];;
- : int array = [|1; 2; 3|]

Note that array literals improve upon C-style (e.g. C and Java) array declarations because OCaml's array literals can be used anywhere (they are expressions) whereas the C-style is only valid on the right-hand side of an array declaration. For example, you can apply an array literal as a function argument directly in OCaml:

# Array.fold_left ( + ) 0 [|1; 2; 3|];;
- : int = 6

Perl[edit]

my @arr = qw(1 2 3);
my @two_dim = ([qw(1 2 3)], [qw(4 5 6)], [qw(7 8 9)]);

PHP[edit]

<?php

$array = array(1, 2, 3, 4, 5);

// or, using the range operator:
$array = range(1, 5);


// Multidimensional
$array = array( array(0, 1, 2), array(3, 4, 5), array(6, 7, 8) );

// or, using the range operator:
$array = array( range(0, 2), range(3, 5), range(6, 8) );

?>

Ruby[edit]

The array element is an optional object ( including an array, too ). All array are variable length.

ary = []
ary = [1, 2.3, [4, 5], "string", true]
ary = Array.new                         #=> []
ary = Array.new(3)                      #=> [nil, nil, nil]
ary = Array.new(3,0)                    #=> [0, 0, 0]
ary = Array.new(3){|i| 2*i}             #=> [0, 2, 4]

# Two dimension
ary = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
ary = Array.new(3){|i| Array.new(3,i)}  #=> [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
ary = Array.new(3){|i| Array.new(3){|j| 3*i + j}}
                                        #=> [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

Visual Basic (3-6)[edit]

One Dimensional[edit]

Fixed Length Array:

 Dim Variable(5) as string

Variable Length Array:

 Dim Variable() as string

Two Dimensional[edit]

Fixed by Fixed Length Array:

 Dim Variable(5,2) as string

Fixed by Variable Length Array:

 Dim Variable(5,) as string

Variable by Variable Length Array:

 Dim Variable(,) as string

Zsh[edit]

Associative arrays

set -A array key value
or
typeset -A array # Before assignment!
or
array=(key value)

Ordinary arrays

typeset -a array # Before assignment!
or
array=(value)