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

Create a free website or blog at WordPress.com.

%d bloggers like this: