|
| HOW TO CREATE ARRAYS
There are many ways to create an array. The method you use will naturally depend on your coding circumstances.
Arrays, like variables, are created when a value is assigned to it.
$name[0]="John Marks";
The array $name has been created and holds a single value of John Marks.
Creating with multiple values:
$color[1]="blue";
$color[2]="white";
$color[3]="red";
$color[4]="yellow";
The array $color is created that holds four values: blue, white, red, yellow.
The numbers between [ ] are keys. Keys can also be a strings as below:
$person['name']="blue";
$person['email']="white";
To create an array, you don't need to specify a key like above. Below is also a way to create an array:
$name[ ]="Mike";
If you don't specify a key as above, the key is automatically assigned as a serialised number starting from 0.
An array can also be created as follows:
$fruit=array('apple', 'banana', 'orange', 'peach');
This will be equivalent to:
$fruit[0] will hold apple
$fruit[1] will hold banana
$fruit[2] will hold orange
$fruit[3] will hold peach
Notice that the keys automatically start at 0 and increment up sequentially.
If we want the keys to start at something else, we can do:
$fruit=array(20 => 'apple', 'banana', 'orange', 'peach');
This will be equivalent to:
$fruit[20] will hold apple
$fruit[21] will hold banana
$fruit[22] will hold orange
$fruit[23] will hold peach
We can also assign strings as keys as follows:
$person=array('name' => 'John', 'email' => 'john@somesite.com', 'country' => 'India');
This will be equivalent to:
$person['name'] will hold John
$person['email'] will hold john@somesite.com
$person['country'] will hold India
Arrays can also be created with a function taking a range of values as below:
$ages=range(30, 35);
This will be equivalent to:
$ages[0] will hold 30
$ages[1] will hold 31
$ages[2] will hold 32
$ages[3] will hold 33
$ages[4] will hold 34
$ages[5] will hold 35
See also:
|
|