IntroductionAn array is a complex variable that allows us to store multiple values in a single variable. An array variable is as a "container" variable that contains one or more values. An Array in PHP is actually an ordered map. A map is a type that associates a value with keys. This type is optimized for several uses. For example we can be treat them as an array, a list, hash table, dictionary, collection, stack, queue and probably more.
Syntax of an Array
- $Arr= array('value1', 'value2', 'value3',.....);
An array can be created using the array() constructor. It takes any number of values and each value is separated by a comma and every value should be associated with their keys.
- array(
- key =>value1,
- key =>value2,
- key =>value3,
- ...
- )
The comma after the last array element is optional and can be omitted. For example a single-line array such as array(100,200) is preferred instead of array(100,200,). In the multi-dimensional array, a comma after the last value of the array will add a new value at the end.
Example
- <?php
- $arr= array(
- student1 =>"rajeev",
- student2 =>"ranjan",
- );
- $arrayExample = [
- "student1"=>"rajeev",
- "student2"=>"ranjan",];
- ?>
As of PHP 5.4 we can use an array with the following technique to replace array() with [].
The key can be an integer or a string.
Example of Type Casting and Overwriting
- <?php
- $array = array(1 => "W","1" => "X",1.5 => "Y",true => "Z",);
- var_dump($array);
- ?>
In this example all the values are overwritten into a key and all keys are cast into one. In other words 1=> d . In this case PHP cannot distingue between an integer and a string at runtime.
Example of Indexed arrays without key
- <?php
- $arr= array("hello","world",);
- var_dump($arr);
- ?>
var_dump(): This function displays structured information about one or more expressions that include its type and value. Arrays and Objects are explored recursively with the values indented to show the structure.
Example of arrays with key
- <?php
- $arr=array("a","b","c",5=>"d","e","f",);
- var_dump($arr);
- ?>
Example of Accessing the value of an array
- <?php
- $arr = array("first" => "hello",99 => 2014,"multi" => array("dimensional" => array("array" =>"hello world!")));
- var_dump($arr["first"]);
- var_dump($arr[99]);
- var_dump($arr["multi"]["dimensional"]["array"]);
- ?>
In this above example we see $arr[] with square brackets to access the array value. But curly braces are also used to access the array value.
Example of Array dereferencing
- <?php
- $array = array(1, 2, 3, 4, 5);
- print_r($array);
- echo("<br/>");
- foreach ($array as $i => $value) {
- unset($array[$i]);
- }
-
- print_r($array);
- echo("<br/>");
- $array[] = 6;
- print_r($array);
- echo("<br/>");
- $array = array_values($array);
- $array[] = 7;
- print_r($array);
- ?>
The unset() function allows us to remove the keys from the array. The array_value() function helps us to reindex the keys.
PHP Array Function
Array_change_key_case()
This function changes the case of all keys in an array.
Syntax
array array_change_key_case( array $arr [, int $case= CASE_LOWER] )
Returns an array with its keys converted to lower or uppper case, or FALSE if it is not an array.
arr: This is the array for which the operation will be performed.
case: Default case is always lower, but for upper case we can use CASE_UPPER.
NOTE: This function throws an E_WARNING if the item is not an array.
- <?php
- $Arr = array("RaJeEv" => 1, "RaNjAn" => 2,);
- print_r(array_change_key_case($Arr, CASE_UPPER));
- ?>
array_chunk()
This function splits an array into a number of chunks.
Syntax
array array_chunk (array $arr, int $size [, bool $preserve_keys = false ] )
This function returns the number of multi-dimensional numerically indexed arrays, starting with zero.
arr: This is the array for which the operation will be performed.
size: Size of the chunk.
preserve_keys: Key will preserved if it is set to TRUE. In the case of FALSE the key value starts at zero in each chunk.
- <?php
- $arr = array('a', 'b', 'c', 'd', 'e');
- print_r(array_chunk($arr, 2));
- echo '<br/>';
- print_r(array_chunk($arr, 2, true));
- ?>
array_column()
Syntax
array array_column( array $arr , mixed $column_key [, mixed $index_key = null ] )
array_column() returns the value from a single column of the specified array.
arr: This is the array for which the operation will be performed.
column_key: Column key might be an integer or a string, that is passed to the function for retrieving the column.
index_key: The column to use the index/key to return the array.
- <?php
- $records = array(
- array( 'id' => 201, 'Name' => 'rohit', 'Address' => 'pune', ),
- array( 'id' => 202, 'Name' => 'rajeev', 'Address' => 'delhi', ),
- array( 'id' => 203, 'Name' => 'kunal', 'Address' => 'new delhi', ),
- array( 'id' => 204, 'Name' => 'solanki', 'Address' => 'ahmadabad', ),
- array( 'id' => 205, 'Name' => 'gouvav lahe', 'Address' => 'pune', ),
- array( 'id' => 206, 'Name' => 'swapnil kamble', 'Address' => 'ranchi', ) );
- print_r(array_column($records,'Name'));
- ?>
array_combine()
This function creates an array using a key and another by value.
Syntax
array array_combine( array $keys, array $values)
keys: Array of keys to be used. Illegal values for the key will be converted to a string.
values: Array of value is used.
This functions returns the combined array.
- <?php
- $TeamA = array('sachin tendulakar', 'sourabh ganguly', 'zaheer khan');
- $TeamB = array('virat kohali', 'suresh raina', 'Anil kumble');
- $TeamC = array_combine($TeamA, $TeamB);
- print_r($TeamC);
- ?>
array_count_values()
This function counts all the values of an array.
Syntax
array array_count_values (array $arr)
arr: The array of the value to count.
- <?php
- $arr= array("1","1","2","3","red","2","red","2","red","yellow","1",);
- print_r(array_count_values($arr));
- ?>
array_diff_assoc()
This function helps to find the difference between two arrays with their values.
Syntax
array array_diff_assoc( array $array1, array $array2 [, array $... ] )
array1: An array to compare from.
array2: An array to compare against.
This function returns the difference (unmatched fields) value in an array and the difference in the terms of array1 and array2.
- <?php
- $arr1 = array("A" => "Apple", "B" => "Ball", "C" => "Cricket", "Rose");
- $arr2 = array("A" => "Apple", "Ball", "ROse");
- $output = array_diff_assoc($arr1, $arr2);
- print_r($output);
- ?>
array_diff_key()
Syntax
array array_diff_key( array $array1, array $array2 [, array $...] )
array1: First parameter to use for the comparison.
array2: Second parameter to use for the comparison.
This function compares the keys of array 1 and array 2 and returns the value in an array. It returns an array whose keys are not present in array 1 from the comparing array. The comparison from the keys between arrays is something like [$key1 ===$key2]. We can say that this function is a strict type check, so that the strings must be the same. This function is such as array_diff() but the only difference is the keys instead of the values.
- <?php
- $array1=array("player1"=>"Dinesh","player2"=>"rahul","player3"=>"Raina");
- $array2=array("player3"=>"Rohit","player4"=>"Dhoni","player5"=>"A.B.Devilers");
- $array3=array("player6"=>"sachin","player3"=>"virat","player7"=>"sourabh");
- $result=array_diff_key($array1,$array2,$array3);
- print_r($result);
- ?>
array_diff_uassoc()
Syntax
array array_diff_uassoc ( array $array1 , array $array2 [, array $... ] , callable $key_compare_function )
- array1: First parameter to use for the comparison.
- array2: Second parameter is use for the comparison.
- key_compare_function: This function must return the an integer <,=, or > than 0 if the first argument is considered to be respectively <,> or = then the second.
This function also compares two arrays with an additional index check that is done by user logic with a callback function. This function returns an array having all the entries from array1 that are not present in any other array. In simple words it compares the keys and values of two (or more) arrays and returns an array having the array with an unmatched value in another comparing array.
- <?php
- function myfunction($a,$b){
- if ($a===$b){
- return 0;
- }
- return ($a>$b)?1:-1;
- }
- $a1=array("1"=>"rohit","2"=>"sachin","3"=>"zaheer");
- $a2=array("5"=>"red","2"=>"sachin","5"=>"gautam");
- $result=array_diff_uassoc($a1,$a2,"myfunction");
- print_r($result);
- ?>
array_diff_ukey()
Syntax
array array_diff_ukey ( array $array1 , array $array2 [ , array $... ] , callable $key_compare_function )
- array1: First parameter to use for the comparison.
- array2: Second parameter to use for the comparison.
- key_compare_function: This function must return the an integer <,=, or > than 0 if the first argument is considered to be respectively <,> or = then the second.
This function gets the difference of arrays among the passed array on the basis of a key. This function only compares the key and returns the resulting array as not array2 and array3 and so on.
- <?php
- function myfunction($a,$b){
- if ($a===$b){
- return 0;
- }
- return ($a>$b)?1:-1;
- }
- $array1=array("a"=>"red","b"=>"green","c"=>"blue");
- $array2=array("a"=>"black","b"=>"yellow","d"=>"brown");
- $result=array_diff_ukey($array1,$array2,"myfunction");
- print_r($result);
- ?>
array_diff()
Syntax
array array_diff ( array $array1, array $array2 [, array $ ... ] )
- array1: First parameter to use for the comparison.
- array2: Second parameter is use for the comparison.
This function compares the first array to the other one or more arrays and returns the values in the array that are not present in the other array.
- <?php
- $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
- $a2=array("e"=>"red","f"=>"black","g"=>"purple");
- $a3=array("a"=>"red","b"=>"black","h"=>"yellow");
- $result=array_diff($a1,$a2,$a3);
- print_r($result);
- ?>
array_fill_keys()
Syntax
array array_fill_keys ( array $keys, mixed $value )
keys: Key is an array of values and an illegal value is converted into a string.
value: That is passed into the array.
This function is used to fill an array with a value and the value is passed by the specified key. This function returns an array with filled values.
- <?php
- $keys = array('Rajeev', 2, 7, 'Ranjan');
- $a = array_fill_keys($keys, 'Hello World');
- print_r($a);
- ?>
array_fill()
Syntax
array array_fill ( int $start_index , int $num , mixed $value )
- start_index: The first index of the returned array.
- num: Specifies the number of elements to insert.
- value: Specifies the value to use for filling the array.
This function helps us to fill the data into an array within a number of values and the starting point of the array index. This function will return a filled array.
- <?php
- $arr1 = array_fill(7, 6, 'Hello');
- $arr2 = array_fill(-1, 4, 'Rajeev');
- print_r($arr1);
- echo "<br/>";
- print_r($arr2);
- ?>
array_filter()
Syntax
array array_filter ( array $array = array() [ , callable $callable = function() ] )
- array: The array to be filtered.
- callable: callable function for the filter logic.
This function filters the value of an array using a callable function; this function passes each value of the input array to the callable function. The Array key is preserved when the callable value returns true.
- <?php
- function odd($var){
- return($var & 1);
- }
- function even($var){
- return(!($var & 1));
- }
- $array1 = array("a"=>101, "b"=>102, "c"=>103, "d"=>104, "e"=>105);
- $array2 = array(106, 107, 108, 109, 110, 111, 112);
- echo "Odd :\n";
- print_r(array_filter($array1, "odd"));
- echo "<br/>Even:\n";
- print_r(array_filter($array2, "even"));
- ?>
array_flip()
Syntax
array array_flip (array $array)
array: Parameter of the array of the array key or value pairs to be flipped.
This function will exchange all keys with their associated values and return an array as output but flipped. The value of an array should be a valid key (either an integer or string ). If the key is not valid then it will show an error or warning message and the most important is if a value occurs multiple times then the latest key will be used as its value and the other will be lost.
- <?php
- $flipped = array("a" => 1, "b" => 1, "c" => 2);
- $flipped = array_flip($flipped);
- print_r($flipped);
- ?>
array_intersect
Syntax
array array_intersect ( array $array1 , array $array2 [, array $... ])
- array1:The first parameter is the master value to check.
- array2: The second and other arrays are compared by their value against the master value.
This function returns an array having all the field values common to all. In simple words intersect means all the common values among all the associated arrays. In the intersected array the keys of the array will preserved.
There are also some associated intersect functions in PHP, they are the following.
array_intersect_assoc(): Intersect the array with an index check. If the key value does not match then this function will not intersect.
array_intersect_key(): Intersect in behalf of the key.
array_intersect_uassoc(): Compare other arrays on the basis of keys but not like the array_intersect() function, with a callable function instead.
array_intersect_ukey(): Compute the intersection of arrays using a callable function on the key for comparison.
- <?php
- $class1 = array("st1" => "rajeev", "st2" => "rohit", "st3" => "ashok", "subham");
- $class2 = array("st1" => "RAJEEV", "st2" => "rohit", "ankit", "chandan");
- print_r(array_uintersect($class1, $class2, "strcasecmp"));
- ?>
Sorting and searching in Array using functions
Sort()
Syntax
bool sort ( array $array [ , int $sort_flag = SORT_REGULAR ] )
array: The input array to sort.
sort_flag: This second parameter is optional, either you can provide the sorting flags or not.
Sorting type flags
- SORT_REGULAR: Compare items normally.
- SORT_NUMERIC: Compare items numerically.
- SORT_STRING: Compare items as string.
- SORT_LOCAL_STRING: Compare items as strings, based on the current locale. setlocale() method is used to change the local.
- SORT_NATURAL: Compare items as string using "natural order" natsort().
- SORT_FLAG_CASE: This case can be combined with bitwise OR with SORT_STRING or SORT_NATURAL.
This function sorts an array. Elements of an array are arranged from the lowest to the highest. It returns TRUE on success or FALSE on failure.
- <?php
- $crickter = array("zaheer", "dhoni", "raina", "ajit");
- sort($crickter);
- foreach ($crickter as $key => $val) {
- echo "crickter[" . $key . "] = " . $val . "<br/>";
- }
- ?>
There are also some more sorting functions as specified below.
- asort(): Sort an array in reverse order and keep their index association. This function is mainly used in associative arrays.
- rsort(): Sort an array in reverse order.
- ksort(): Sort an array by key and maintain the key for data correlation. Mainly used in associative arrays.
- usort(): Sort an array by its values using a callable user defined function.
- natsort(): Sort an array using a natural ordering algorithm.
- arsort(): Sort an array in reverse order and maintain an index association.
- uksort(): Sort an array by keys using a user-defined compare function.
- uasort(): Sort an array by keys using a user-defined compare function and maintain the index association.
- krsort(): Sort an array by key in reverse order.
- natcasesort(): Sort an array using a case insensitive natural order algorithm.
- array_multisort(): Sort multiple or multi-dimensional arrays
array_search()
Syntax
mixed array_search (mixed $value , array $array1 [ , bool $strict = false ] )
value: The first parameter is the value to be searched.
array1: The second parameter is the array1 for which the action is to be performed.
strict: If the third parameter is set to TRUE then it will search for identical objects from the array by type and the object must be the same instance.
- <?php
- $array = array(0 => 'anmol', 1 => 'kritish', 2 => 'nagesh', 3 => 'manish');
- $key = array_search('manish', $array);
- echo "key value of manish is =" .$key. "<br/>";
- $key = array_search('anmol', $array);
- echo "key value of anmol is =" .$key;
- ?>
Push & Pop in PHP
array_push(): This function adds one or more elements onto the end of the array.
array_pop(): This function pops (removes) one element from the end of the array.
array_pad(): pad the array to the specified length with the value.
- <?php
- $input = array(7,8,44);
- $result = array_pad($input, 5, 0);
- print_r($result);
- echo "<br/>";
- $result = array_pad($input, -7, -1);
- print_r($result);
- echo "<br/>";
- $result = array_pad($input, 2, "noop");
- print_r($result);
- ?>
Summary
In this article we covered many topics of array functions like array_flip, intersect an array, various sorting functions, searching, push, pop and pad functions in brief.