“Array” is one of the most vital parts of every programming language. It is also important to know what facilities and built-in functionality a programming language provides. PHP provides a very strong set of efficient ways to deal with the array of different data types. From time to time, I have discovered several uses of PHP arrays, saving me time and making writing code efficient. I often need to revisit these functions to memorize and use them again. In this article, I will briefly describe some of the most often used function references, which I think will be helpful as my future reference. I hope some readers will benefit as well. Let’s start with knowing the available types if you are new or not certainly sure about them.
Types Of PHP Arrays:
First, it is good to know how many types of arrays there are in the PHP programming language. There are three basic types:
Indexed Array: Arrays with sequential numeric index, such as 0,1,2 etc. Example:
$myarray = array();
$myarray[0] = "test data 1";
$myarray[1] = "test data 2";
$myarray[3] = "test data 3";
Code language: PHP (php)
Associative Array: This is the most frequently used type of PHP Array whose elements are defined in key/value pair.Example:
$myarray = array();
$myarray["key1"] = "value 1";
$myarray["key2"] = "value 2";
$myarray["key3"] = "value 3";
Code language: PHP (php)
Multidimensional Array: Arrays whose elements may contain one or more arrays. There is no limit to the level of dimensions. Example:
$myarray = array();
$myarray[0] = array("data01","data02","data03");
$myarray[1] = array("data11","data12","data13");
Code language: PHP (php)
Let’s look into some frequently used and useful array operations:
Merge Two Arrays Into a Single One:
The “array_merge” function provides the easiest way to merge a list of arrays. It can take as many parameters as you give it, and it will merge all of them into a single one and return them to you. Example usage:
$myarray1 = array(1,2,3);
$myarray2 = array(4,5,6);
$myarray3 = array(7,8,9);
$single_merged_array = array_merge($array1,$array2,$array3);
print_r($single_merged_array);
Code language: PHP (php)
Sorting Arrays In PHP:
There are two ways to sort elements of the array. If you want a simple default ascending order sorting with non-object array elements, you can go for the “sort” function. You pass the array as a parameter, and it will sort the array and return it as true if successful.
$simple_array = array("dbc","bcd,"abc");
if(sort($simple_array)){
print_r($simpl_array);
}
Code language: PHP (php)
If you want to define your logic for sort condition and/or you are using objects as elements of the array, go for the “usort” function. Example:
$elements = array();
$elements[0] = (object)NULL;
$elements[0]->post_time = new DateTime();
$elements[1] = (object)NULL;
$elements[1]->post_time = new DateTime();
usort($elements,"sort_function");
function sort_function( $a, $b ) {
return $b->post_time->diff($a->post_time)->invert;
}
Code language: PHP (php)
Difference Between Two PHP Arrays:
If you are trying to exclude a few elements from an array which are common to another array’s elements, then “array_diff” is the perfect function for you. Use as below:
$myarray1 = array(1,2,3,4,-1,-2);
$myarray2 = array(-1,-2);
$filtered_array = array_diff($myarray1,$myarray2);
print_r($filtered_array);
Code language: PHP (php)
Get Common Elements Among Two PHP Arrays:
If you are trying to get only the common elements from two different arrays, “array_intersect” is the proper function for such a purpose. A simple PHP example for this operation is given below:
$myarray1 = array(1,2,3,4,-1,-2);
$myarray2 = array(-1,-2,3);
$common_array = array_intersect($myarray1,$myarray2);
print_r($common_array);
Code language: PHP (php)
Getting Keys/Values Separately From Associative Array:
If you somehow need to get either only the keys or values of an associative array, you can do so with the help of “array_keys” or “array_values” functions. See the example below:
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
print_r(array_keys($my_array));
echo "<br>";
print_r(array_values($my_array));
Code language: PHP (php)
Convert A PHP Array To String And Vice-versa:
I need this one frequently :). Often, I need to convert a string to an array of elements and also convert an array to a single string value with delimited characters like “,” etc. These operations can be achieved by “implode” and “explode” PHP functions. Let’s see their usage:
$myarray1 = array(1,2,3,4,-1,-2);
$converted_string = implode(",",$myarray1);
echo $converted_string;
$converted_values = explode(",",$converted_string);
echo print_r($converted_values);
Code language: PHP (php)
Retrieve Only A Portion Of An Array:
Well, you do have a big array, but at some point, you need only a limited part of it without destroying other elements. In cases like that, “array_chunk” comes to the relief.
$limited_array = array_chunk($my_array,10);
print_r($limited_array);
Code language: PHP (php)
Remove Duplicates From PHP Array:
“array_unique” – another angel function to me :D. It will remove duplicate entries and make the array contain only distinct elements. Just pass the array as its parameter, and we will be done! If you are trying to make unique elements of object type, then make sure to implement your own _toString() function inside the class and return a string value that represents the identity of the object. It should do the work fine.
$unique_array = array_unique($my_array_with_duplicates);
print_r($unique_array);
Code language: PHP (php)
Final Words:
If you are looking for more PHP array function references, you can always dig into the official php.net site’s array references, which contain a hell lot of more implementations. If you have any specific questions about any type of array operation described above, please feel free to ask them here in the comments. Happy coding 🙂
ieldor says
Nice choice of php array references. Although, need to proofread the spelling mistakes of the article before posting. Happy Coding:)
Md.Rofiquil Islam says
Thanks Brother for your learning co-operation
Javed Ur Rehman says
Md Ali thanks bro for sharing such a great arrays tutorial with us, really helpful for our developer brothers. 🙂
Rajan Shrivastava says
thank’s
ab says
arr=array(1,1,1,1,1,1,0,1,1,1,0,1,1,1,1); 0 should be always comes in first place and second last place ,how to do this in given array
Biplab Das says
$FirstHalfName=array();
foreach ($fisrtHalfArr as $key => $menuid) {
$menuItem =”SELECT * FROM “.$CFG[‘table’][‘restaurant_menu’].” WHERE id = ‘”.$menuid.”‘ “;
$MenuQuery = $this->ExecuteQuery($menuItem ,’select’);
$FirstHalfName[$key]=$MenuQuery[0];
}
tcyadmin says
Not very good examppe. Explain more
Santhosh says
Thanks!
Ashwini Shelar says
how to sort multidimensional array according to value without using any sort function.