SANGKRIT

Arrays

Scalar variables store only one value at a time. They cannot store a list of values.

Arrays are special types of variables which can store a list of values at a time.

An array can include a list of days in a week.

Arrays are indexed; each entry contains a key and a value.

Here, the values stored in array are known as elements.

Each element is referenced by an index that identifies the element by any unique element in the array.

The index value can be a number or string but it should be unique.

Associative and Numeric Arrays:

Numeric arrays use numbers as their indexes.

Associative arrays use strings as their indexes.

An example of numeric array:

Key Value 
0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday
6 Sunday

 

An example of associative array:

Key Value 
One Monday
Two Tuesday
Three Wednesday
Four Thursday
Five Friday
Six Saturday
Seven Sunday

Internally PHP stores the numeric array same as the associative array.

 

How to create an array:

An array can be created by the array() function or the array operator [].

The following example shows how to create an array called $week using the array() function, containing all days of the week:

$week = array(“Monday”, “Tuesday”, Wednesday”, “Thursday”, Friday”, “Saturday”, “Sunday”);

If you create an array using array function then also you an list the last elements using an array operator:

$week = array(“Monday”, “Tuesday”, Wednesday”, “Thursday”, Friday”, “Saturday”);

$week[] = “Sunday”;

Following is the same array created by using an array operator[]:

$week[0] = “Monday”;

$week[1] = “Tuesday”;

$week[2] = “Wednesday”;

$week[3] = “Thursday”;

$week[4] = “Friday”;

$week[5] = “Saturday”;

$week[6] = “Sunday”;

In case if you misnumber your elements then PHP will arrange them in correct way.


 

3 thoughts on “Arrays”

Leave a Reply