On Sat, Jun 8, 2013 at 3:13 AM, Pierre du Plessis <[email protected]>wrote:
>
> function my_call_back($key, $value) {
>> return array($value, strlen($value));
>> }
>> $array = str_word_count("PHP is lots of fun!");
>> $array = array_map_key('my_call_back', $array);
>>
>>
>> The result would be the following array:
>>
>> array(5) {
>> ["PHP"]=>
>> int(3)
>> ["is"]=>
>> int(2)
>> ["lots"]=>
>> int(4)
>> ["of"]=>
>> int(2)
>> ["fun"]=>
>> int(3)
>> }
>>
>>
> This example doesn't make any sense, as str_word_count returns an
> integer, so you would in fact pass an int to array_map_key and not an array.
>
My mistake, I left out the second argument to str_word_count, which should
have been 1. In that case str_word_count would return an array of all the
words in supplied string.
>
> But let's say using your example, you use explode(" ", $string) instead of
> str_word_count, which will give you an array of all the words.
>
> What happens in the following case:
>
> function my_call_back($key, $value) {
> return array($value, strlen($value));
> }
> $array = str_word_count("PHP stands for PHP hypertext preprocessor");
>
> $array = array_map_key('my_call_back', $array);
>
>
> This would give you 2 keys with the value of PHP. What happens in this
> case?
> What if you have duplicate integer keys. Does the keys simply increment or
> throw an error?
>
The same thing that would happen if you did $array['PHP'] = 3;
$array['PHP'] = 3; The value would be overridden.
array_map_key would behave no differently than foreach would in this
matter. The code would semantically equivalent to the following:
function array_map_key(Callable $callback, $array) {
$return = array();
foreach ($array as $key => $value) {
list($k,$v) = $callback($key, $value);
$return[$k] = $v;
}
return $return;
}
You can see the PHP user-land implementation here with your
described example and the resulting output http://3v4l.org/pe855