CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Programming 8 Most Frequently Used And Useful PHP Array Operations

8 Most Frequently Used And Useful PHP Array Operations

Rana Ahsan April 27, 2013 9 Comments


 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 🙂

Related

Filed Under: Programming Tagged With: php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. ieldor says

    August 13, 2013 at 3:34 am

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

    Reply
  2. Md.Rofiquil Islam says

    June 27, 2015 at 2:09 pm

    Thanks Brother for your learning co-operation

    Reply
  3. Javed Ur Rehman says

    July 31, 2015 at 1:49 am

    Md Ali thanks bro for sharing such a great arrays tutorial with us, really helpful for our developer brothers. 🙂

    Reply
  4. Rajan Shrivastava says

    August 31, 2016 at 4:54 am

    thank’s

    Reply
  5. ab says

    October 25, 2016 at 2:02 am

    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

    Reply
  6. Biplab Das says

    March 21, 2017 at 12:36 am

    $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];

    }

    Reply
  7. tcyadmin says

    November 26, 2017 at 11:02 am

    Not very good examppe. Explain more

    Reply
  8. Santhosh says

    July 9, 2018 at 1:26 am

    Thanks!

    Reply
  9. Ashwini Shelar says

    May 25, 2020 at 7:44 am

    how to sort multidimensional array according to value without using any sort function.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in