Jump to: navigation, search

Php array map

From w3cyberlearnings

Contents

PHP function array_map

This function creates a new array by calling each array value and sends to the function to check. The function will modify each array value and return.

Syntax array_map

  • callback: user-defined function uses to manipulate the array value
  • array: array to be manipulated by the callback function.
array_map(callback,array);

Example 1

<?php

$name = array('cambodia',
	 'vietnam',
	 'thailand',
	 'lao',
	 'malaysia',
	 'indonesia',
	 'singapore'
);

$aa_name = array_map('ucfirst', $name);
foreach ($aa_name as $n) {
	echo $n . '<br/>';
}
?>


Output


Cambodia
Vietnam
Thailand
Lao
Malaysia
Indonesia
Singapore

Example 2

<?php

function add_code($va) {
	$code = array(
		 'cambodia' => 855,
		 'vietnam' => 845,
		 'thailand' => 392,
		 'lao' => 322,
		 'malaysia' => 311,
		 'indonesia' => 344,
		 'singapore' => 773
	);
	return "{$va}:{$code[$va]}";
}

$name = array('cambodia',
	 'vietnam',
	 'thailand',
	 'lao',
	 'malaysia',
	 'indonesia',
	 'singapore'
);

$aa_name = array_map('add_code', $name);
foreach ($aa_name as $n) {
	echo $n . '<br/>';
}
?>

Output

cambodia:855
vietnam:845
thailand:392
lao:322
malaysia:311
indonesia:344
singapore:773

Example 3

<?php

function add_score($val) {
	if ($val > 32) {
		return ($val + 20);
	} else {
		return ($val - 5);
	}
}

$score = array(
	 'john' => 31,
	 'bob' => 30,
	 'mark' => 32
);

$score_list = array_map("add_score", $score);
foreach ($score_list as $name => $new_score) {
	echo "{$name} new score is {$new_score}.<br/>";
}
?>


Output


john new score is 26.
bob new score is 25.
mark new score is 27.

Related Links


Navigation
Web
SQL
MISC
References