PHP array is an variable which stores the multiple values of related data in a single variable.
Creating an PHP array
1 2 3 4 5 6 |
array( key => value, key2 => value2, key3 => value3, ... ) |
array() function is used to create an array.
The key can either be an integer or a string. The value can be of any type.
It takes any number of comma-separated key => value pairs as arguments.
Types of array
For example:
1 2 3 4 |
<?php $arr = array("Tea", "Coffoe", "GreenTea"); ?> |
-
An array index can be any string value, even a value that is also a value in the array.
The value of array[“foo”] is “bar”.
The value of array[“bar”] is “foo” -
The comma after the last array element is optional.
This is usually done when you want to single-line array like array(1,2).
It is preferred than writing array(1,2,).
But for multi-line array is is commonly used because it is easier to add new element at the end of array.
In previous of PHP 5.4 you have to use array() like this, but as of PHP5.4, array() is replace with array[].
For example:
123<?php$arr = array[ "name" => "Mike", "Mike" => "name", ];?> -
The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
For example:
1234<?php$arr = array("Mike", "John", "Robert");var_dump($arr);?>
Output:
12345array(3) {[0]=> string(4) "Mike"[1]=> string(4) "John"[2]=> string(6) "Robert"} -
You can specify only key for some elements and leave others.
For example:
123456789<?php$arr = array("a","b",3 => "c","d",);var_dump($arr);?>
Output:
123456array(4) {[0]=> string(1) "a"[1]=> string(1) "b"[3]=> string(1) "c"[4]=> string(1) "d"}
Here, you can see from output the last value “d” was assigned the key 4.
This is because PHP increment the previous integer key i.e. 3.