Array in PHP

Introduction

An 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

  1. $Arrarray('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.

  1. array(  
  2. key =>value1,  
  3. key =>value2,  
  4. key =>value3,  
  5. ...  

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

  1. <?php  
  2. $arrarray(  
  3. student1 =>"rajeev",  
  4. student2 =>"ranjan",  
  5. );  
  6. $arrayExample = [  
  7. "student1"=>"rajeev",  
  8. "student2"=>"ranjan",];  
  9. ?> 

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

  1. <?php  
  2. $array = array(1 => "W","1" => "X",1.5 => "Y",true => "Z",);  
  3. var_dump($array);  
  4. ?> 

Example1_revised

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

  1. <?php  
  2. $arrarray("hello","world",);  
  3. var_dump($arr);  
  4. ?> 

example2IndexedArray_revised

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

  1. <?php  
  2. $arr=array("a","b","c",5=>"d","e","f",);  
  3. var_dump($arr);  
  4. ?> 

example3KeyValueInArray_revised

Example of Accessing the value of an array

  1. <?php  
  2. $arr = array("first" => "hello",99 => 2014,"multi" => array("dimensional" => array("array" =>"hello world!")));  
  3. var_dump($arr["first"]);  
  4. var_dump($arr[99]);  
  5. var_dump($arr["multi"]["dimensional"]["array"]);  
  6. ?> 

example4AccessingArray_revised

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

  1. <?php  
  2. $array = array(1, 2, 3, 4, 5);  
  3. print_r($array);  
  4. echo("<br/>");  
  5. foreach ($array as $i => $value) {  
  6.                 unset($array[$i]);  
  7.         }  
  8.   
  9. print_r($array);  
  10. echo("<br/>");  
  11. $array[] = 6;  
  12. print_r($array);  
  13. echo("<br/>");  
  14. $array = array_values($array);  
  15. $array[] = 7;  
  16. print_r($array);  
  17. ?> 

ArrayDereferencing_revised

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.

  1. <?php  
  2. $Arr = array("RaJeEv" => 1, "RaNjAn" => 2,);  
  3. print_r(array_change_key_case($Arr, CASE_UPPER));  
  4. ?> 

Array_Change_Case_revised
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.

  1. <?php  
  2. $arr = array('a''b''c''d''e');  
  3. print_r(array_chunk($arr, 2));  
  4. echo '<br/>';  
  5. print_r(array_chunk($arr, 2, true));  
  6. ?> 

Array_chunk_revised

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.

  1. <?php  
  2. $records = array(  
  3. array'id' => 201, 'Name' => 'rohit''Address' => 'pune', ),  
  4. array'id' => 202, 'Name' => 'rajeev''Address' => 'delhi', ),  
  5. array'id' => 203, 'Name' => 'kunal''Address' => 'new delhi', ),  
  6. array'id' => 204, 'Name' => 'solanki''Address' => 'ahmadabad', ),  
  7. array'id' => 205, 'Name' => 'gouvav lahe''Address' => 'pune', ),  
  8. array'id' => 206, 'Name' => 'swapnil kamble''Address' => 'ranchi', ) );  
  9. print_r(array_column($records,'Name'));  
  10. ?> 

Array_column_revised
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.

  1. <?php  
  2. $TeamA = array('sachin tendulakar''sourabh ganguly''zaheer khan');  
  3. $TeamB = array('virat kohali''suresh raina''Anil kumble');  
  4. $TeamC = array_combine($TeamA$TeamB);  
  5. print_r($TeamC);  
  6. ?> 

array_combine_revised
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.

  1. <?php  
  2. $arrarray("1","1","2","3","red","2","red","2","red","yellow","1",);  
  3. print_r(array_count_values($arr));  
  4. ?> 

array_count_values_revised

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.

  1. <?php  
  2. $arr1 = array("A" => "Apple""B" => "Ball""C" => "Cricket""Rose");  
  3. $arr2 = array("A" => "Apple""Ball""ROse");  
  4. $output = array_diff_assoc($arr1$arr2);  
  5. print_r($output);  
  6. ?> 

Array_diff_assoc_revised

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.

  1. <?php  
  2. $array1=array("player1"=>"Dinesh","player2"=>"rahul","player3"=>"Raina");  
  3. $array2=array("player3"=>"Rohit","player4"=>"Dhoni","player5"=>"A.B.Devilers");  
  4. $array3=array("player6"=>"sachin","player3"=>"virat","player7"=>"sourabh");  
  5. $result=array_diff_key($array1,$array2,$array3);  
  6. print_r($result);  
  7. ?> 
Array_diff_keys_revised

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.

  1. <?php  
  2. function myfunction($a,$b){  
  3. if ($a===$b){  
  4. return 0;  
  5. }  
  6. return ($a>$b)?1:-1;  
  7. }  
  8. $a1=array("1"=>"rohit","2"=>"sachin","3"=>"zaheer");  
  9. $a2=array("5"=>"red","2"=>"sachin","5"=>"gautam");  
  10. $result=array_diff_uassoc($a1,$a2,"myfunction");  
  11. print_r($result);  
  12. ?> 

Array_diff_uassoc_revised

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.

  1. <?php  
  2. function myfunction($a,$b){  
  3. if ($a===$b){  
  4. return 0;  
  5. }  
  6. return ($a>$b)?1:-1;  
  7. }  
  8. $array1=array("a"=>"red","b"=>"green","c"=>"blue");  
  9. $array2=array("a"=>"black","b"=>"yellow","d"=>"brown");  
  10. $result=array_diff_ukey($array1,$array2,"myfunction");  
  11. print_r($result);  
  12. ?> 

Array_diff_ukey_revised
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.

  1. <?php  
  2. $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");  
  3. $a2=array("e"=>"red","f"=>"black","g"=>"purple");  
  4. $a3=array("a"=>"red","b"=>"black","h"=>"yellow");  
  5. $result=array_diff($a1,$a2,$a3);  
  6. print_r($result);  
  7. ?> 

Array_diff_revised

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.

  1. <?php  
  2. $keys = array('Rajeev', 2, 7, 'Ranjan');  
  3. $a = array_fill_keys($keys'Hello World');  
  4. print_r($a);  
  5. ?> 

Array_fill_key_revised

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.

  1. <?php  
  2. $arr1 = array_fill(7, 6, 'Hello');  
  3. $arr2 = array_fill(-1, 4, 'Rajeev');  
  4. print_r($arr1);  
  5. echo "<br/>";  
  6. print_r($arr2);  
  7. ?> 

Array_fill_revised

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.

  1. <?php  
  2. function odd($var){  
  3. return($var & 1);  
  4. }  
  5. function even($var){  
  6. return(!($var & 1));  
  7. }  
  8. $array1 = array("a"=>101, "b"=>102, "c"=>103, "d"=>104, "e"=>105);  
  9. $array2 = array(106, 107, 108, 109, 110, 111, 112);  
  10. echo "Odd :\n";  
  11. print_r(array_filter($array1"odd"));  
  12. echo "<br/>Even:\n";  
  13. print_r(array_filter($array2"even"));  
  14. ?> 

Array_filter_revised

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.

  1. <?php  
  2. $flipped = array("a" => 1, "b" => 1, "c" => 2);  
  3. $flipped = array_flip($flipped);  
  4. print_r($flipped);  
  5. ?> 

Array_flip_revised

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.

  1. <?php  
  2. $class1 = array("st1" => "rajeev""st2" => "rohit""st3" => "ashok""subham");  
  3. $class2 = array("st1" => "RAJEEV""st2" => "rohit""ankit""chandan");  
  4. print_r(array_uintersect($class1$class2"strcasecmp"));  
  5. ?> 

Array_intersect_revised

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.

  1. <?php  
  2. $crickter = array("zaheer""dhoni""raina""ajit");  
  3. sort($crickter);  
  4. foreach ($crickter as $key => $val) {  
  5. echo "crickter[" . $key . "] = " . $val . "<br/>";  
  6. }  
  7. ?> 

sort_revised

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.

  1. <?php  
  2. $array = array(0 => 'anmol', 1 => 'kritish', 2 => 'nagesh', 3 => 'manish');  
  3. $key = array_search('manish'$array);  
  4. echo "key value of manish is =" .$key"<br/>";  
  5. $key = array_search('anmol'$array);  
  6. echo "key value of anmol is =" .$key;  
  7. ?> 

Array_srch_revised

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.

  1. <?php  
  2. $input = array(7,8,44);  
  3. $result = array_pad($input, 5, 0);  
  4. print_r($result);  
  5. echo "<br/>";  
  6. $result = array_pad($input, -7, -1);  
  7. print_r($result);  
  8. echo "<br/>";  
  9. $result = array_pad($input, 2, "noop");  
  10. print_r($result);  
  11. ?> 

Array_pad_revised
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.


Similar Articles