note 68016 deleted from function.array-walk by philip
| From: | philip@php.net | Date: | Tue, 11 Jul 2006 06:36:47 +0000 |
| Subject: | note 68016 deleted from function.array-walk by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-114658@lists.php.net to get a copy of this message | ||
Note Submitter: legolas558 dot sourceforge comma net
----
Sorry for the previous wild post, which was incorrect too
---
to <ludvig dot ericson at gmail dot com>
I would solve the problem in the following way, which should be faster too.
Note that the assignment to $string{$i} will use only the first character from the return value of
the user callback function, so it is useless to return strings longer than 1 characters.
<?php
function string_walk(&$string, $funcname, $userdata = null) {
for($i = 0; $i < strlen($string); $i++)
$string{$i} = call_user_func($funcname, $string{$i}, $i, $userdata);
}
// does nothing
function dummy_func($value, $position) {
return $value;
}
// adds a space
function spacing_func($value, $position) {
echo $value.' ';
return $value;
}
// converts each odd character to upper case
function upper_func($value, $position) {
if ($position % 2 == 0)
return $value;
else
return strtoupper($value);
}
$my_string = 'fruit';
string_walk(&$my_string, 'spacing_func');
// Ouput: f r u i t
$my_string = 'interesting';
string_walk(&$my_string, 'upper_func');
echo $my_string;
// Output: iNtErEsTiNg
?>