PHP/Data Structure/array map
Applying Functions to Array Elements Using array_map()
<?php
function array_display($array, $pre=FALSE)
{
$tag = $pre ? "pre" : "p";
printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag);
}
function calc_sqrt($num)
{
$i = $num < 0 ? "i" : "";
return sqrt( abs($num) ) . $i;
}
$values = array(3, 8, -3, 0, 14, -4);
$roots = array_map("calc_sqrt", $values);
print "<p>Values:</p>";
array_display($values, TRUE);
print "<p>Square roots:</p>";
array_display($roots, TRUE);
?>
Using array_map() and array_walk() together
<?php
function array_display($array, $pre=FALSE)
{
$tag = $pre ? "pre" : "p";
printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag);
}
function get_pay($emp, $hr, $rt)
{
return sprintf("%s worked %.2f hours, and grossed $%.2f",
$emp, $hr, $rt * $hr);
}
function display_pd_emp(&$el)
{
printf("<p>%s.</p>\n", $el);
}
$employees = array("A", "B", "C", "D", "N");
$hours = array(35.2, 37.4, 41.3, 28.8, 38.5);
$rates = array(12.5, 12.5, 13.75, 9.85, 11.6);
$paid_emps = array_map("get_pay", $employees, $hours, $rates);
array_walk($paid_emps, "display_pd_emp");
array_display($paid_emps, TRUE);
?>
Using the array_map() Function
<?php
function my_callback($var) {
echo "Value: $var<BR>";
return strtoupper($var);
}
$myarray = array("hello", "this", "is", "a", "callback!");
$newarray = array_map("my_callback", $myarray);
echo "<PRE>";
print_r($newarray);
echo "</PRE>";
?>