Arrays

Array stores multiple values.

Initialization

There are couple of ways to initialize array:

Empty array

Initial values

In this example an array with 3 elements is created.

Size

Size is the count of elements in array.

It's accessed via the count function.

Output:

Accessing values

Array's values can be accessed via indexes starting from 0.

If we declare the following array:

It's elements are:

array-indexing

So if we type the following line:

It will print:

Index out of Bounds

Accessing index outside of the array results in warning and returns value of null.

Let's have an array with 4 elements. If we access the 4th or higher index null will be returned.

Such example is:

Output:

Printing All Elements

Let's have an example in which all elements of array are printed.

Output:

foreach loop is convenient but for loop could be used too.

Inserting Elements

Elements can be inserted using [] or the array_push function.

Let's have a program which fills array with values:

Product Of Elements

Let's have a program which calculates the product of all even numbers:

Output:

The only even numbers in the array are 2 and 4 which are multiplied.