Perform operations (code) on each item of an array we are imploding without traversing the array twice?

StackOverflow https://stackoverflow.com/questions/21578666

  •  07-10-2022
  •  | 
  •  

문제

Is there a way to perform operations on each items of an array we are imploding without traversing the array twice?

I've run into lambda-based solutions but it traverses the array twice (unless I'm wrong):

$array = array('some','boring','items');
$func = function($arr){
    $return = array();
    foreach ($arr as $item) {
        $return[] = ucfirst($item);
    }
    return $return;
};
echo ' ' . implode('#', $func($array));

A pretty old report exists on PHP bugtracker but no practical solution were given.

I would like to avoid recoding implode like such:

$iter = new ArrayIterator($array);
while ($iter->valid()) {
    echo ucfirst($iter->current());
    $iter->next();
    if ($iter->valid()) {
        echo '#';
    }
}
도움이 되었습니까?

해결책

Sure, why not. Just use function call in-place, like:

$array = array('some','boring','items');

$result = substr(array_reduce($array, function(&$cur, $x)
{
   return $cur.='#'.ucfirst($x);
}, ''), 1);

Alternatively (if you want to avoid even string overhead when doing substr()) - use

$result = ucfirst(array_shift($array)).array_reduce($array, function(&$cur, $x)
{
   return $cur.='#'.ucfirst($x);
}, '');

-less "beautiful" - but certainly will use each element only once.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top