Skip to content

Instantly share code, notes, and snippets.

@rtt
Created December 3, 2012 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtt/4197086 to your computer and use it in GitHub Desktop.
Save rtt/4197086 to your computer and use it in GitHub Desktop.
php type coercion callback
<?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