Data
Array
PHP
$arr1 = [1, 2, 3];
$arr2 = array(1, 2, 3);
Array is a container for a sequence of items.
There are 2 main ways to create Arrays.
- Literal syntax
- array function
The elements inside the Array don't need to have the same type.
The bracket ([]) syntax is introduced in PHP 5.4.
Arrays in PHP can be associative. You can learn more about that in the Map topic.
$arr = [1, 2, 3];
$length = count($arr); // 3
Function count()
returns the length of an Array.
$animals = ["Cat", "Dog", "Cow"];
$cat = $animals[0]; // Cat
Array elements can be accessed by their index.
In PHP, the Array Index starts from 0.
$animals = ["Cat", "Dog", "Cow"];
$animals[0] = "Lion";
Here we are setting an element at index 0 to a value Lion.
So now animals
array values are Lion, Dog, Cow.
$arr = [1, 2, 3];
$arr[] = 4; // arr -> [1,2,3,4]
You can append an element to the end of the Array using []
.
$animals = ["Cat", "Dog", "Cow"];
$index = array_search("Dog", $animals); // 1
Function array_search()
search in an array and returns:
- first found element index in index-based array.
- first found element key in associative array.
If the element does not exist, it returns false.
$animals = ["Cat", "Dog", "Cow"];
$sub1 = array_slice($animals,2); // $sub -> ["Cow"]
$sub2 = array_slice($animals,2,1); // $sub -> ["Cow"]
Function array_slice()
gets start (inclusive) and the length of SubArray and returns the SubArray for those parameters.
If you don't specify the length of the SubArray, slice()
will return the SubArray from starting point to the end of the Array.
$arr = [2, 4, 3, 1];
sort($arr); // arr -> [1,2,3,4]
Function sort()
order an Array elements in Ascending order and returns true on success and false on failure.
Other PHP functions for sorting arrays are:
sort
- sort arrays in ascending order.rsort
- sort arrays in descending order.asort
- sort associative arrays in ascending order, according to the valueksort
- sort associative arrays in ascending order, according to the keyasort
- sort associative arrays in descending order, according to the valuekrsort
- sort associative arrays in descending order, according to the key
$animals = ["Cat", "Dog", "Cow"];
$str1 = implode(',', $animals); // "Cat,Dog,Cow"
$str2 = json_encode($animals); // ["Cat","Dog","Cow"]
$str3 = serialize($animals); // s:11:"Cat,Dog,Cow";
$str4 = print_r($animals, true);
/*
Array
(
[0] => Cat
[1] => Dog
[2] => Cow
)
*/
Based on your needs you can use any of the functions below:
implode
json_encode
serialize
print_r