Created
December 3, 2012 18:54
-
-
Save rtt/4197086 to your computer and use it in GitHub Desktop.
php type coercion callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$converters = array( | |
'string' => function($s) { return $s.' boobs'; }, | |
'integer' => function($i) { return $i + 1; } | |
); | |
$vals = array( | |
1 => 1, | |
'str' => 'moar', | |
); | |
$coerced = array_map(function($el) use ($converters) { | |
$t = gettype($el); | |
return array_key_exists($t, $converters) ? $converters[$t]($el) : $el; | |
}, $vals); | |
print_r($vals); | |
print_r($coerced); | |
/* | |
$vals before: | |
Array | |
( | |
[1] => 1 | |
[str] => moar | |
) | |
$coerced after: | |
Array | |
( | |
[1] => 2 | |
[str] => moar boobs | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment