Implode and Explode Array then wrap it inside a sample data

264 views Asked by At

I have a string that looks like this:

$str = "Col1, Col2, Col3";

My question is how can I make it look like this

FORMAT(SUM('Col1'),2),FORMAT(SUM('Col2'),2),FORMAT(SUM('Col3'),2)

I am trying to use implode and explode but it's not working for me.

Here is my attempt:

$sample = "Col1, Col2, Col3";
$test = explode(",", $sample);
$test = "'" . implode("', FORMAT(SUM('", $test) . "), 2";
2

There are 2 answers

0
Andrei Todorut On BEST ANSWER
$sample = "Col1,Col2,Col3";
$test= explode(',',$sample);
$_test = '';
foreach($test as $t){
    $_test .= "FORMAT(SUM('$t'),2),";
}

$_test = rtrim($_test,',');
0
Manuel Mannhardt On

I dont know if you can achiev this using explode, but you for sure can using a foreach loop.

$sample = 'Col1,Col2,Col3';
$result = '';
$parts = explode(',', $sample);
foreach ($parts as $part) {
    $result .= 'FORMAT(SUM(' . $part . '), 2)';
    $result .= (end($parts) !== $part) ? ', ' : '';
}

This runs over each part of the exploded array and adds the desired string plus a comma if its not the last element.


You can also use array_walk to achieve the requested result:

$sample = 'Col1,Col2,Col3';
$parts = explode(',', $sample);
$str = '';
array_walk($parts, function ($element) use (&$str) {
    $str .= 'FORMAT(SUM(' . $element . '), 2), ';
});

$result = rtrim($str, ', ');