Fold in comments to array_map()

Co-authored-by: Kamil Tekiela <tekiela246@gmail.com>

Closes GH-828.
This commit is contained in:
Larry Garfield 2021-07-30 11:18:35 -05:00 committed by GitHub
parent ab57ab6849
commit d042804100
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -22,7 +22,9 @@
used as arguments for the callback.
The number of parameters that the <parameter>callback</parameter>
function accepts should match the number of arrays
passed to <function>array_map</function>.
passed to <function>array_map</function>. Excess
input arrays are ignored. An <classname>ArgumentCountError</classname>
is thrown if an insufficient number of arguments is provided.
</para>
</refsect1>
@ -122,11 +124,16 @@ Array
<programlisting role="php">
<![CDATA[
<?php
$func = function($value) {
$func = function(int $value): int {
return $value * 2;
};
print_r(array_map($func, range(1, 5)));
// Or as of PHP 7.4.0:
print_r(array_map(fn($value): int => $value * 2, range(1, 5)));
?>
]]>
</programlisting>
@ -150,12 +157,12 @@ Array
<programlisting role="php">
<![CDATA[
<?php
function show_Spanish($n, $m)
function show_Spanish(int $n, string $m): string
{
return "The number {$n} is called {$m} in Spanish";
}
function map_Spanish($n, $m)
function map_Spanish(int $n, string $m): array
{
return [$n => $m];
}
@ -371,6 +378,44 @@ array(1) {
string(5) "value"
}
}
]]>
</screen>
</example>
<example>
<title><function>array_map</function> - associative arrays</title>
<para>
While <function>array_map</function> does not directly support
using the array key as an input, that may be simulated using <function>array_keys</function>.
</para>
<programlisting role="php">
<![CDATA[
<?php
$arr = [
'v1' => 'First release',
'v2' => 'Second release',
'v3' => 'Third release',
];
// Note: Before 7.4.0, use the longer syntax for anonymous functions instead.
$callback = fn(string $k, string $v): string => "$k was the $v";
$result = array_map($callback, array_keys($arr), array_values($arr));
var_dump($result);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(3) {
[0]=>
string(24) "v1 was the First release"
[1]=>
string(25) "v2 was the Second release"
[2]=>
string(24) "v3 was the Third release"
}
]]>
</screen>
</example>