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 .