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
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_ exists
- array_keys