|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2005-01-22 22:08 UTC] zizka at seznam dot cz
Description:
------------
array_map could take non-array parameters and pass them to the callback function in each step.
Example:
$a = explode(' ', 'XyX aXb sXs');
$a = array_map('str_replace', 'X','Y', $a);
That would result in calling:
str_replace('X','Y', $a[...]);
and the result array would be like
Array('YyY', 'aYb', 'sYs');
Now I have to define a callback function for many simple operations that could be done this way.
Thanks, Ondra Zizka
Reproduce code:
---------------
$a = explode(' ', 'XyX aXb sXs');
$a = array_map('str_replace', 'X','Y', $a);
print_r($a);
Expected result:
----------------
Array( [0] => YyY [1] => aYb [2] => sYs )
Actual result:
--------------
Warning: array_map() [function.array-map.htm]: Argument #2 should be an array in ...
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 18:00:01 2025 UTC |
Another solution is to pass arrays with several identical members: $a = explode(' ', 'XyX aXb sXs'); $a = array_map('str_replace', Array('X','X','X'), Array('Y','Y','Y'), $a); But the arrays are superfluous in this case, as a scalar value would be enough. And with this case there is a problem that the supplementary arrays must be of at least the same length as $a: PHP Manual: "Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, the shortest one will be extended with empty elements."Anonymous functions don't obviate the usefulness of scalar arguments to array_map (from the 3rd argument onwards, anyway). To work around this, use array_fill(). Using the previous example, this would be: $a = array_map('str_replace', $a, array_fill(0, count($a), 'X'), array_fill(0, count($a), 'Y'));