This article shows arrays in PHP, including:
- Create arrays.
- Sort arrays.
- Traverse array.
- Merge, splice, slice and dissect arrays.
- Output and test for an array.
Introduction
An array is a collection of values of the same data type. In PHP the array concept goes further in the manner that in PHP an array stores each item as a key and value pair. Keys can be numeric vales or can be associative (as a string). These numeric values determine the position of each item in the array.
Creating an Array in PHP
Numeric index example
- $user=array(0=>"sandeep",1=>"rahul",2=>"pankaj");
- Or
- $user[0] = " sandeep";
- $user[1] = " rahul";
- $user[2] = " pankaj";
This stores values of multiple names in each index. If the index is not provided then it will automatically increment the index for continuous value assignment as in the following:
- $user[] = " sandeep";
- $user[] = " rahul";
- $user[] = " pankaj";
Associative Index example
By associative index we provide a meaning to every index, like if we want to denote multiple countries by their nickname then it will be as follows:
$country=array("IND"=>"INDIA","US"=>"UNITED STATES");
Then we can access INDIA by referencing
$country["IND"].
Multidimensional Array
We can create arrays of arrays, in other words multidimensional arrays. For example we can make a student's marks in various subjects as follows.
- <?php
- $student=array
- (
- "HINDI"=>array("marks"=>"96","grade"=>"1st"),
- "ENGLISH"=>array("marks"=>"92","grade"=>"1st")
- );
- foreach($student as $subject=>$sub)
- {
- foreach($sub as $marks=>$number)
- {
- echo "$marks = "," $number ";
- }
- echo "
- <br/>";
- }
- ?>
The output will be as follows:
marks = 96 grade = 1st
marks = 92 grade = 1st
Here we can reference a single item as follows:
$student["HINDI"]["marks"]
This gives the output:
96
Here basically we use either a numeric or an associative index but the key features present here is an array pointer although we actually didn’t use it.
Get array element using list()
TList has the same functionality as an array. list() provides a convenient method to assign one by one a variable value in the list extracted from an array in just one operation. This is maybe usually used when extracting data from a database of from file.
The following is an example:
- <?php
- $array = [
- ["hello", "hey"],
- ["yes", "hello"],
- ];
- foreach ($array as list($a, $b))
- {
- // $a contains the first element of the nested array,
- // and $b contains the second element.
- echo "A: $a; B: $b\n";
- }
- ?>
The output is as follows:
A: hello; B: hey A: yes; B: hello
Explanation: Here we define a 2D array and its value is assigned one by one in the list and then we print those elements. If we simply implement it as in in the previous example.
list($a)
then it only prints:
A: hello; A: yes;
range() function for array
The range function makes a quick array filled with integer numbers. It’s syntax looks like:
range(int low, int high [,int step])
For example we want to make an array that contain 6 numbers as in the following:
- <?php
- $id=range(1,6);
- // Same as specifying $id = array(1, 2, 3, 4, 5, 6)
- $id1=range(1,8,2);
- $id2=range("A","Z",3);
- foreach($id as $value)
- echo "$value ";
- echo "
- <br/>";
- foreach($id1 as $value)
- echo "$value ";
- echo "
- <br/>";
- foreach($id2 as $value)
- echo "$value ";
- ?>
That gives the following output:
1 2 3 4 5 6
1 3 5 7
A D G J M P S V Y
Output Explanation: In the preceding example for $id we just provide a range from 1 to 6 and the difference between each number is 1 by default.
For $id1 we start from 1 to 8 but there is the difference between 2 that we provided to it.
For $id2 we print the range from A to Z and the difference between each character is 3. This difference and calculation is basically done on each character ASCII value.
The range() function not always increments the ASCII, it makes a loop from the start value to the end value.
Testing for an array
Sometimes we need to verify whether the given variable is an array. Then this can be verified using the built-in function
is_array(). It’s syntax looks as follows.
Boolean is_array(variable)
The preceding function returns
true if the passed variable is an array else it returns
false.
- <?php
- $states = array("Rajasthan");
- $state = "Haryana";
- printf("\$states is an array: %s
- <br />", (is_array($states) ? "TRUE" : "FALSE"));
- printf("\$state is an array: %s
- <br />", (is_array($state) ? "TRUE" : "FALSE"));
- ?>
This gives the following output:
$states is an array: TRUE
$state is an array: FALSE
Outputting an array
The output of array's element can be done by iterating each key and this is simply accomplished by a
foreach() loop. This can be as follows:
- <?php
- $id=range(6,1);
- foreach($id as $value)
- echo "$value ";
- ?>
This gives the following output:
6 5 4 3 2 1
For arrays of array elements we can use the vprintf() function that allows us to easily display array contents using the same formatting syntax used by the printf() and sprintf() functions. If we want to send the output to the string, in other words store it in a string then we can use the
vsprintf() function as in the following:
- <?php
- $user = array();
- $user[] = array("sandeep jangid", "[email protected]", "98989898");
- $user[] = array("sanjeev baldia", "[email protected]", "818546454");
- $user[] = array("rahul prajapat", "[email protected]", "212545485");
- foreach ($user AS $customer)
- {
- vprintf("
- <p>Name: %s
- <br />E-mail: %s
- <br />Phone: %s
- </p>", $customer);
- }
- ?>
This produces following output:
Name: sandeep jangid
E-mail: [email protected]
Phone: 98989898
Name: sanjeev baldia
E-mail: [email protected]
Phone: 818546454
Name: rahul prajapat
E-mail: [email protected]
Phone: 212545485
The print_r() function
The print_r() function accepts a variable and sends its contents to standard output, returning TRUE on success and FALSE otherwise. It is usually used for testing an array output. It makes an array content into readable format. It’s syntax looks like this.
boolean print_r(mixed variable [, boolean return])
The following:
- <?php
- $country=array("IND"=>"INDIA","US"=>"UNITED STATES");
- print_r($country);
- ?>
Produces the following output:
Array ( [IND] => INDIA [US] => UNITED STATES )
If we want only to output the array values then this can be done using the optional parameter of print_r(variable, true) function to true otherwise false.
So if we use print_r($country,true) as in our previously example then it produces the following output:
INDIA UNITED STATES
Adding or removing array element
PHP provides a number of functions to shift, pop, push, shrink an array.
Those methods are:
- array_unshift()=adds elements to the front of the array.
- array_push()=adds values to the end of the array and returns the total count of the array element.
- array_shift()=removes and returns the first item found in an array.
- array_pop()=removes and returns the last element from an array.
Note: In all the preceding array functions, after performing any add and remove operation, the index values of the array will be modified depending on their respective function but associative keys never get a change.
Let’s see, the following:
- <?php
- $arr=array("user1","user2","user3","user4","user5");
- array_unshift($arr,"user0");
- //this give array("user0","user1","user2","user3","user4","user5")
- array_push($arr,"user6");
- //this give array("user0","user1","user2","user3","user4","user5","user6")
- array_shift($arr);
- //this give array("user1","user2","user3","user4","user5","user6")
- array_pop($arr);
- //this give array("user1","user2","user3","user4","user5")
- foreach($arr as $arr)
- echo "$arr ";
- ?>
Gives the following output:
user1 user2 user3 user4 user5
Locating array element
Searching an array element: The in_array() function searches an array for a specific value, returning TRUE if the value is found and FALSE if fails to be found. Its syntax is as follows.
boolean in_array(string to be found, in which array want to found [, boolean strict])
Here the third parameter strict is to make our searching type specific or not.
Consider the following example:
- <?php
- $arr=array("user1","user2","user3","user4");
- if(in_array("user55",$arr))
- echo "element found";
- else
- echo "Element not found";
- ?>
That gives the following output:
Element not found
Searching associative array keys
This uses the array_key_exists() function to find a specific key in an associative array. For example:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- if(array_key_exists("user1",$arr))
- echo "element found";
- else
- echo "element not found";
- ?>
This gives the following output:
elemant found
Searching associative array values
This uses the array_key_exists() function to find a specific value in an associative array and returns it’s key. For example:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- $hel=array_search("sandeep",$arr);
- echo "$hel";
- ?>
This gives the following output:
user1
Retrieving array keys
The array_keys() function returns an array consisting of all keys located in an array. Its prototype follows.
array array_keys(array variable [, search_value to be specific search [, boolean preserve_keys]])
Here search_value if included then only the keys that will be matched are shown. Setting the optional preserve_keys parameter to true will cause the array value's keys to be preserved in the returned array. The following:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- $hel=array_keys($arr);
- print_r($hel);
- ?>
Produces the following output:
Array ( [0] => user1 [1] => user2 [2] => user3 [3] => user4 )
Retrieving array values: The array_values() function returns an array consisting of all keys located in an array. The following:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- $hel=array_values($arr);
- print_r($hel);
- ?>
Produces the following output:
Array ( [0] => sandeep [1] => pankaj [2] => rahul [3] => neeraj )
Traversing Array
Get current array key
To get the current array key we use the
key() function to provide the first index value and in the following example we use
next() to increment the key.
The following:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- while($keykey = key($arr))
- {
- printf("%s
- <br />", $key);
- next($arr);
- }
- ?>
Produces the output as follows:
user1
user2
user3
user4
Get current array value
To get the current array key we use the
current() function to give us the first index value and in the following example we use
next() to increment the key.
The following:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- while($value = current($arr))
- {
- <br />", $value);
- next($arr);
- }
- ?>
Produces the following: output:
sandeep
pankaj
rahul
neeraj
Get current array’s key value pair
To get an array’s current key value pair we can use the
each() function that takes an array name as argument and automatically increments to the next key after retrieving the first key value pair. If the pointer is residing at the end of the array before executing each(), FALSE is returned.
The following:
- <?php
- $arr=array("user1"=>"sandeep","user2"=>"pankaj","user3"=>"rahul","user4"=>"neeraj");
- while(list($key,$value)=each($arr))
- {
- echo "$key $value ";
- }
- ?>
Gives the following output:
user1 sandeep user2 pankaj user3 rahul user4 neeraj
Move array pointer to Next or Previous position
To move an array pointer to the next position we use the
next() function and to move an array pointer in the previous direction we use the
prev() function. As we have already seen, the
next() function example in the previous example.
Moving the Pointer to the First and Last Array Position
The
reset() function sets an array pointer back to the beginning of the array. This function is commonly used when we need to review or manipulate an array multiple times within a script, or when sorting has completed whereas the
end() function sets the array pointer to the last element of the array and returns that element.
The following:
- <?php
- $fruit=array("apple","mango","banana","orange");
- $first=reset($fruit);
- echo "$first ";
- $last=end($fruit);
- echo "$last";
- ?>
Produces the following output:
apple orange
Passing array values to a function
- To pass an array’s values to a function we use the array_walk() function.
- This function will pass each element of the array to a user-defined function.
- This is useful when we want to perform specific kind of functions on each array element.
- If we send an array as a reference then it will be completely changed for the entire scope.
Its syntax is as follows:
boolean array_walk(array &array, callback function name [, mixed userdata])
The following:
- <?php
- $arr=array("user1"=>"apple ","user2"=>"mango ","user3"=>"orange ");
- function sanitize_data($value, $key)
- {
- $value = strip_tags($value);
- echo "$value ";
- }
- array_walk($arr,"sanitize_data");
- ?>
Produces the following output:
apple mango orange
Explanation: here we first define an associative array (we can also use an indexed array). Then we define a function sanitize_data() that takes the two parameters $value and $key. This $value and $key are obtained when
the
array_walk () function is called by sanitize_data() and passes
$arr in the parameter.
strip_tags() is a predefined function for concatenating strings.
If we are working with an array of arrays then we use the
array_walk_recursive() function.
Determining the Size of an Array
The
count() function returns the total number of values found in an array. The sizeof() function is similar to count(). Its syntax follows.
integer count(array array [, int mode]
If the optional
mode parameter is enabled (set to 1), the array will be counted recursively. This is useful when counting all elements of a multidimensional array. The following example counts the total number of vegetables found in the $fruit array:
- <?php
- $fruit = array("mango", "apple", "orange", "pomegranate");
- echo count($fruit);
- ?>
This returns the following:
4
The next example counts both the scalar values and array values found in $cities.
- <?php
- $cities = array("alwar", "jaipur", array("udaipur","kota"), "mathura");
- echo count($cities, 1);
- ?>
It returns the following:
6
Count value frequency in array
It counts how many times a value in an array repeats and to do this it uses the function
array_count_values() that returns an array with the number of counts.
For example:
- <?php
- $garden = array("cabbage", "peppers", "turnips", "carrots","cabbage","carrots");
- $result=array_count_values($garden);
- print_r($result);
- ?>
Produces the following result:
Array ( [cabbage] => 2 [peppers] => 1 [turnips] => 1 [carrots] => 2 )
Get unique array values
It gets unique values from an array using array_unique() and it returns an array that consists of distinct values.
For example:
- <?php
- $garden = array("cabbage", "peppers", "turnips", "carrots","cabbage","carrots");
- $result=array_unique($garden);
- print_r($result);
- ?>
Produces the following result:
Array ( [0] => cabbage [1] => peppers [2] => turnips [3] => carrots )
Sorting Arrays
The element in an array can be sorted in numeric or alphabetic order and/or ascending or descending order.
We use the following PHP array functions.
Function Name |
Description |
sort() |
sort arrays in ascending order |
rsort() |
sort arrays in descending order |
asort() |
sort associative arrays in ascending order, depending on the value |
ksort() |
sort associative arrays in ascending order, depending on the key |
arsort() |
sort associative arrays in descending order, depending on the value |
krsort() |
sort associative arrays in descending order, depending on the key |
natsort() |
It sorts an array naturally like (3.jpg, 1.jpg) to (1.jpg, 3.jpg) |
natcasesort() |
It works similar as natsort() but case sensitive |
Flipping Array Keys and Values
The array_flip() function reverses the roles of the keys and their corresponding values in an array.
The following is an example:
- <?php
- $state = array("rajasthan", "haryana", "punjab");
- $state = array_flip($state);
- print_r($state);
- ?>
This example returns the following:
Array ( [punjab] => 0 [haryana] => 1 [rajasthan] => 2 )
User-defined array sorting
The
usort() function provides a convenient way for user-defined sorting. The syntax is as follows.
usort(array array,called function name)
The example is as follows:
- <?php
- function my_sort($a,$b)
- {
- if ($a==$b) return 0;
- return ($a<$b)?-1:1;
- }
- $a=array(4,2,8,6);
- usort($a,"my_sort");
- foreach($a as $a)
- echo "$a ";
- ?>
This produces the following output:
2 4 6 8
Merging, Slicing, Splicing, and Dissecting Arrays
Merging Array: The array_merge() function merges two arrays and returns a single obtained array that has shuffled values.
For example:
- <?php
- $face = array("J", "Q", "K", "A");
- $numbered = array("2", "3", "4", "5", "6", "7", "8", "9");
- $cards = array_merge($face, $numbered);
- shuffle($cards);
- print_r($cards);
- ?>
This produces the following output and it can be different on each refresh.
Array ( [0] => 5 [1] => K [2] => Q [3] => 2 [4] => A [5] => 6 [6] => 9 [7] => J [8] => 4 [9] => 7 [10] => 3 [11] => 8 )
Recursively Appending Arrays: The array_merge_recursive() function merges two arrays. The same as done by the array_merge() function but the difference is when merging both arrays if there is more than one key/value pair in the array then it merges the values together and make the pre-existing key as it’s name.
The example is as follows:
- <?php
- $class1 = array("sandeep" => 100, "rahul" => 85);
- $class2 = array("sandeep" => 18, "pankaj" => 45);
- $classResult = array_merge_recursive($class1, $class2);//sandeep is repeated
- print_r($classResult);
- ?>
This produces the following output:
Array ( [sandeep] => Array ( [0] => 100 [1] => 18 ) [rahul] => 85 [pankaj] => 45 )
Note: In result a new array created whose name is sandeep
Combining two Arrays: The array_combine() function results a new array consisting of a submitted set of keys and corresponding values. Its prototype follows.
array array_combine(array keys, array values)
The submitted set of arrays should be of equal size and neither can be empty.
The example as follows:
- <?php
- $abbr = array("IND", "UK", "AUS", "US");
- $countries = array("India", "United Kingdom", "Australia", "United States");
- $countryMap = array_combine($abbr,$countries);
- print_r($countryMap);
- ?>
The output is as follows:
Array ( [IND] => India [UK] => United Kingdom [AUS] => Australia [US] => United States )
Slicing an array: The array_slice() function returns a subset or section of array based on the starting and ending offset value.
It’s syntax is as follows:
array array_slice(array array, int offset [, int length [, boolean save_key]])
A positive offset value will slice to begin offset positions from the beginning of the array. A negative offset value will slice offset positions from the end of the array. If the
optional length parameter is absent, the slice will start at the offset and end at the last element of the array. If the length is provided and is positive, it will end at the
offset + length position from the beginning of the array. Conversely, if length is provided and is negative, it will end at the
count(input_array) – length position from the end of the array. If the optional parameter
save_key is provided and set to true then the array key position will not be changed in the result.
Consider the following example:
- <?php
- $veg = array("cabbage", "peppers", "turnips", "carrots","potato","tomato");
- $subset = array_slice($veg, 2, -2,true);
- print_r($subset);
- ?>
This produces the following output:
Array ( [2] => turnips [3] => carrots )
Array Intersection
The result of the
array_intersect() is the array whose values is common to each array variable in another array. It considers the values to be identical if they have the same data type. For an associative array intersection we use the
array_intersect_assoc() function.
Its syntax is as follows:
array array_intersect (array array1,array array2,…. Up to N)
For example:
- <?php
- $arrayarray1 = array("Oa", "Cz", "Nx", "Hu", "Cv");
- $arrayarray2 = array("Oa", "sA", "Hu", "Nx", "Ia");
- $arrayarray3 = array("Te", "Ma", "Nx", "Oa", "Hu");
- $intersection = array_intersect($array1, $array2, $array3);
- print_r($intersection);
- ?>
This produces the following output:
Array ( [0] => Oa [2] => Nx [3] => Hu )
Note: Just the opposite of
array_intersect() we use the
array_diff() function that returns the values located in the first array that are not located in any of the subsequent arrays and use the
array_diff_assoc() function for the associative array.
The following is a list of the array related functions.
Function |
Description |
array() |
Creates an array |
array_change_key_case() |
Changes all keys in an array to lowercase or uppercase |
array_chunk() |
Splits an array into chunks of arrays |
array_column() |
Returns the values from a single column in the input array |
array_combine() |
Creates an array using the elements from one "keys" array and one "values" array |
array_count_values() |
Counts all the values of an array |
array_diff() |
Compare arrays, and returns the differences (compare values only) |
array_diff_assoc() |
Compare arrays, and returns the differences (compare keys and values) |
array_diff_key() |
Compare arrays, and returns the differences (compare keys only) |
array_diff_uassoc() |
Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function) |
array_diff_ukey() |
Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function) |
array_fill() |
Fills an array with values |
array_fill_keys() |
Fills an array with values, specifying keys |
array_filter() |
Filters the values of an array using a callback function |
array_flip() |
Flips/exchanges all keys with their associated values in an array |
array_intersect() |
Compare arrays, and returns the matches (compare values only) |
array_intersect_assoc() |
Compare arrays and returns the matches (compare keys and values) |
array_intersect_key() |
Compare arrays, and returns the matches (compare keys only) |
array_intersect_uassoc() |
Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function) |
array_intersect_ukey() |
Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function) |
array_key_exists() |
Checks if the specified key exists in the array |
array_keys() |
Returns all the keys of an array |
array_map() |
Sends each value of an array to a user-made function, that returns new values |
array_merge() |
Merges one or more arrays into one array |
array_merge_recursive() |
Merges one or more arrays into one array recursively |
array_multisort() |
Sorts multiple or multi-dimensional arrays |
array_pad() |
Inserts a specified number of items, with a specified value, to an array |
array_pop() |
Deletes the last element of an array |
array_product() |
Calculates the product of the values in an array |
array_push() |
Inserts one or more elements to the end of an array |
array_rand() |
Returns one or more random keys from an array |
array_reduce() |
Returns an array as a string, using a user-defined function |
array_replace() |
Replaces the values of the first array with the values from the following arrays |
array_replace_recursive() |
Replaces the values of the first array with the values from the following arrays recursively |
array_reverse() |
Returns an array in the reverse order |
array_search() |
Searches an array for a given value and returns the key |
array_shift() |
Removes the first element from an array and returns the value of the removed element |
array_slice() |
Returns selected parts of an array |
array_splice() |
Removes and replaces specified elements of an array |
array_sum() |
Returns the sum of the values in an array |
array_udiff() |
Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function) |
array_udiff_assoc() |
Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) |
array_udiff_uassoc() |
Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions) |
array_uintersect() |
Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function) |
array_uintersect_assoc() |
Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) |
array_uintersect_uassoc() |
Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions) |
array_unique() |
Removes duplicate values from an array |
array_unshift() |
Adds one or more elements to the beginning of an array |
array_values() |
Returns all the values of an array |
array_walk() |
Applies a user function to every member of an array |
array_walk_recursive() |
Applies a user function recursively to every member of an array |
arsort() |
Sorts an associative array in descending order, depending on the value |
asort() |
Sorts an associative array in ascending order, depending on the value |
compact() |
Create array containing variables and their values |
count() |
Returns the number of elements in an array |
current() |
Returns the current element in an array |
each() |
Returns the current key and value pair from an array |
end() |
Sets the internal pointer of an array to its last element |
extract() |
Imports variables into the current symbol table from an array |
in_array() |
Checks if a specified value exists in an array |
key() |
Fetches a key from an array |
krsort() |
Sorts an associative array in descending order, depending on the key |
ksort() |
Sorts an associative array in ascending order, depending on the key |
list() |
Assigns variables as if they were an array |
natcasesort() |
Sorts an array using a case insensitive "natural order" algorithm |
natsort() |
Sorts an array using a "natural order" algorithm |
next() |
Advance the internal array pointer of an array |
pos() |
Alias of current() |
prev() |
Rewinds the internal array pointer |
range() |
Creates an array containing a range of elements |
reset() |
Sets the internal pointer of an array to its first element |
rsort() |
Sorts an indexed array in descending order |
shuffle() |
Shuffles an array |
sizeof() |
Alias of count() |
sort() |
Sorts an indexed array in ascending order |
uasort() |
Sorts an array by values using a user-defined comparison function |
uksort() |
Sorts an array by keys using a user-defined comparison function |
usort() |
Sorts an array using a user-defined comparison function |
The preceding list of functions is referenced from www.w3schools.com.
Summary
Arrays are very important in programming. In PHP the functions provided for arrays are very useful for performing fast operations. Arrays can be used when taking values from a database or from a file and then use that data depending on our convenience.
Thank you for reading. I hope you would like it.