Categories
Technology

PHP Functional Programming – A code snippet

Given a string of comma-separated values, how do you convert each of them into a link of the form:
<a href=”http://–item–.google.com/”>–item–
and return a comma-separated list of these strings?

Snippet 1:

<?php
//Make these links to google.com

$string = "news,reader,mail";

$array_of_string = split(",",$string);

$final = array();

foreach($array_of_string as $item){
	$final[] = "<a href='http://".$item.".google.com/'>$item</a>";
}

echo implode(", ",$final);
?>

Snippet 2 (uses functional constructs):

<?php

//Make these links to google.com

$string = "news,reader,mail";

$array_of_string = split(",",$string);

echo implode(", ",
		array_map(
			create_function('$item',
	'return "<a href='http://".$item.".google.com/'>$item";'
					),$array_of_string
			)
		);

?>