8 Most Frequently Used And Useful PHP Array Operations


 8 Most Frequently Used And Useful PHP Array Operations  
 


Array is one of the most vital part in every programming languages. It is also important to know what facilities and built-in functionality a programming language provides. PHP provides a very strong set of such efficient ways to deal with array data type. Time to time, I have discovered several usage of PHP arrays which not only saved my time but also made writing efficient code. I still often need to revisit these functions to memorize and use again. In this article, I will briefly describe some most often used function references, which I think will be helpful as my personal future reference. I hope, some readers will may get benefits as well. Lets start with knowing the available types, if you are knew or not certainly sure about.

Types Of PHP Arrays:

First it is good to know how may types of arrays are there in 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";
    
  • Associative Array:This is the most frequently used type of PHP Arrays whose elements are defined in key/value pair.Example:
    $myarray = array();
    $myarray["key1"] = "value 1";
    $myarray["key2"] = "value 2";
    $myarray["key3"] = "value 3";
    
  • Multidimensional Array: Arrays whose elements may contains one or more arrays. There is no limit in the level of dimensions.Example:
    $myarray = array();
    $myarray[0] = array("data01","data02","data03");
    $myarray[1] = array("data11","data12","data13");
    

Lets look into some frequently used and useful array operations:

Merge Two Array In PHP Into Single One:

The “array_merge” function provides the easiest way to merge a list of arrays. It can take as much parameters as you give to it and it will merge all of them into a single one and return back 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);

Sorting Arrays In PHP:

there are two ways to sort elements of array. If you want a simple default ascending order sorting with non-object array elements, then you can go for “sort” function. You just pass the array as parameter and it will sort the array and returns true if succeed.

$simple_array = array("dbc","bcd,"abc");
if(sort($simple_array)){
print_r($simpl_array);
}

If you want to define your own logic for sort condition and/or you are using objects as element of array, go for “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;
}

Difference Between Two PHP Arrays:

If you are trying to exclude 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);

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 purpose. 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);

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 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));

Convert An PHP Array To String And Vice-versa:

This one I need frequently :p . 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. Lets 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);

Retrieve Only A Portion Of An Array:

Well you do have a big array, but at some point, you need only 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);

Remove Duplicates From PHP Array:

“array_unique” – another angel function to me :D. It will remove duplicate entries and make the array contains only distinct elements. Just pass the array as its parameter and we are done! If you are trying to make unique elements which are 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 and it should do the work fine.

$unique_array = array_unique($my_array_with_duplicates);
print_r($unique_array);

Final Words:

If you are looking for more php array function references, you can always dig into official php.net site’s array references, which contains a hell lot of more implementations. If you have any specific question of any type of array operation described above, please feel free to ask it here in comments. Happy coding :)

Comments

  1. ieldor says

    Nice choice of php array references. Although, need to proofread the spelling mistakes of the article before posting. Happy Coding:)

Leave a Reply