Priti's Technical Corner

July 7, 2011

Array Manipulation in PHP

Filed under: PHP Array, Technical Articles — Tags: , , — pritisolanki @ 7:01 am

As a hobby I love to help people in technical forum and I end up in interesting array manipulation question. This buddy of mine was trying to use array in optimized way

Problem

$sports = array(‘Baseball’, ‘Soccer’, ‘Tennis’);

$location = array(‘Mumbai’, ‘Delhi’, ‘Pune’);
Output:

Baseball in Mumbai, Soccer in Delhi and Tennis in Pune

Traditional way

First and foremost solution pop up in one’s mind – iterate both the arrays with a help of for loop and construct the string and output the expected output. Mostly every new developer will hop for this solution.

But I wanted to handle this issue in more optimized way so I started looking in to array functions and designed the following small helpful function which will help you to do the same with no for loops.

Most optimized way to resolve – array_map

$sports = array(‘Baseball’, ‘Soccer’, ‘Tennis’);
$location = array(‘Mumbai’, ‘Delhi’, ‘Pune’);
function show_details($arr1,$arr2)
{
return $arr1.’ in ‘.$arr2;
}
$c = array_map(“show_details”, $sports, $location);
print_r($c);

$final_str=implode(“,”,$c);
$comma_pos=strrpos($final_str,’,’);

echo substr($final_str,0,$comma_pos).’ and ‘.substr($final_str,($comma_pos+1),strlen($final_str));

There may exists some other ways to achieve the same output .

Advertisements

3 Comments »

  1. Pretty! This has been an extremely wonderful post. Many thanks for
    providing these details.

    Comment by Link — July 24, 2012 @ 9:07 am

  2. I’m really enjoying the design and layout of your site. It’s
    a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often.
    Did you hire out a designer to create your theme? Exceptional
    work!

    Comment by Savio Mody — July 26, 2012 @ 12:47 pm

  3. When someone writes an piece of writing he/she keeps
    the plan of a user in his/her mind that how
    a user can know it. Therefore that’s why this piece of writing is outstdanding. Thanks!

    Comment by xperia — August 7, 2012 @ 6:02 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: