1

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
  • change $test) to $test.")". Commented Nov 20, 2017 at 7:24
  • your implode function is the wrong review my answer. I change it and get output like as you want. Commented Nov 20, 2017 at 7:33

2 Answers 2

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

$_test = rtrim($_test,',');
Sign up to request clarification or add additional context in comments.

Comments

1

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, ', ');

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.