0

What I want to achieve is the following:

transform an array:

['A','B','C'];

into a string like:

"A is A, B is B, C is C"

Is there any other way than a foreach-loop (like implode) to achieve this?

4
  • 3
    You could use array_map() or array_reduce(). Commented Aug 24, 2016 at 7:21
  • array_map() is possible, but needs a variable assignment, so it can't be used simply, when i want to concatenate it with another string immediately. Commented Aug 24, 2016 at 7:25
  • eval.in/627981 Commented Aug 24, 2016 at 7:26
  • @Anant: thanks. this is the way i do it at the moment - the standard solution. Commented Aug 24, 2016 at 7:31

5 Answers 5

3

If you're not looking to loop through, you could use array_walk() function.

Try this:

$input = ['A','B','C'];

function test_alter(&$item, &$key) {
    $item = $item.' is '.$item;
}
array_walk($input, 'test_alter');
echo implode(', ', $input);

Output:

A is A, B is B, C is C
Sign up to request clarification or add additional context in comments.

3 Comments

I also thought of a solution like that (reference style) - the best solution at the moment. what about printf?...
print_f is used to print using a format specifier. That has nothing to do with converting an array to string.
Why are you making the key variable modifiable by reference? Even if you could, you don't use that variable.
1
$arr = ['A','B','C'];

function myfunction($arr)
{
    return "$arr is $arr";
}

print_r(array_map("myfunction",$arr));
//[0] => A is A [1] => B is B [2] => C is C 

1 Comment

Nice solution. Usable as a one-line like that: echo implode(', ', array_map(function($v){ return "$v is $v"; }, $arr));
0

use below way with array_walk

$arr = ['A','B','C'];
function _print($item2, $key)
{
    echo "$item2 is $item2, ";
}
array_walk($arr, '_print');

or if need to save in string use below

    $arr = ['A','B','C'];
    $str = '';
    function _print($item2, $key)
    {
        global $str;
        $str = $str."$item2 is $item2, ";
    }
    array_walk($arr, '_print');
    echo trim($str,',');

1 Comment

global declaration should only be used when no other method is suitable -- as shown by other answers, global is not needed to generate the desired output string. Generally, you would just pass the $str value as a function argument (and make it modifiable by reference).
0

Here's my recommendation, since you're accustomed to using implode in php, I wrote you a duplicate function that takes a formatter element in your separator. Anywhere you put %x will duplicate the array key like so:

echo implodeDuplicate(" is %x, ", $myArray);

assuming $myArray was:

$myArray = array(1,2,3,4);

it will output:

1 is 1, 2 is 2, 3 is 3, 4 is 4,

Here's the function:

function implodeDuplicate($seperator, $array) {
    $finalString = "";
    for($i = 0; $i < count($array); $i++) {
        $trueSep = str_replace("%x", $array[$i], $seperator);
        $finalString .= $array[$i] . $trueSep;
    }
    return $finalString;
}

Hope it's helpful! :)

3 Comments

Thanks. But too complex :-)
What's to complex about it, or what don't you like? I'll see if I can tweak it for you.
You are doing many things, that are not required to solve the problem. See upvoted solution of yogesh, edited by u_mulder. Its clean, simple and can be directly used as a one-liner.
0

I see array_map() and array_walk() solutions, but no one posted an array_reduce() method, so I will for completeness.

For small arrays (few iterations required), array_map() will execute ever-so-slightly faster (your users will never notice the difference).

As the input array increases in size, array_reduce() takes the lead and distances itself from array_map(). Do your own benchmarks with your own real data if you need to perform micro-optimization.

My following method doesn't need implode() because array_reduce() outputs a string, however it does need a conditional on each iteration to avoid "over-gluing".

Code: (Demo)

$input = ['A', 'B', 'C'];
echo array_reduce(
         $input,
         fn($result, $v) => ($result ? "$result, " : '') . "$v is $v"
     );

Or here is array_map() with arrow function syntax then implode(): (Demo)

echo implode(
         ', ',
         array_map(
             fn($v) => "$v is $v",
             $input
         )
     );

Output:

A is A, B is B, C is C

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.