0

Hi,

I have a string like this:

$coord = "1,0 1,8 7,13 7,94";

and I need to divide by 100 each one of the values to get something like this:

0.01,0 0.01,0.08 0.07,0.13 0.07,0.94

So I tried this:

$pair=explode(" ", $coord);

foreach ($pair as $val) {
    $sing = explode(",", $val);
    foreach ($sing as $div) {
     $res = ($div/100);
    }
    $sing_d = implode(",", $res);
}

$result = implode(" ", $sing_d);

print ($result);

but I get an error:

Warning: implode(): Invalid arguments passed

What is the simplest way to do this?

4
  • 1
    $res is not an array, implode needs an array to be parsed Commented Jun 18, 2016 at 17:18
  • Why is $res not an array? Its inside a foreach. Commented Jun 18, 2016 at 17:26
  • It would have been if you had put $res[] = $div/100. Note the square brackets. Also the (round) parentheses you put are not needed, nor do they make the result an array. Commented Jun 18, 2016 at 17:31
  • Thank you. I got it now. Commented Jun 18, 2016 at 17:33

1 Answer 1

2

You could use preg_replace_callback to find and replace all numbers by their value divided by 100:

$result = preg_replace_callback("/\d+(\.\d+)?/", function ($match) {
    return $match[0]/100;
}, $coord);
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer. I didnt know that function. Its great. Thank you.

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.