0

I have an object which contains currency properties with their respective values. I need to add an extra amount to these, which I have simplified by appending a "+ TAX" value.

But I keep getting "array to string conversion" error on the first line within the foreach. I don't understand why - the values are strings. "

Worst still, the new object property duplicates within itself.

Here's my code

<?php

$result = new stdClass();
$result->GBP = "10.00";
$result->USD = "12.00";


foreach ($result as $currency => $value) {
   $currencyWithTax = $value .' + TAX';
   $result->total[$currency] = $currencyWithTax;
}

print_r($result);

I created an 3v4l here to demonstrate.

So I get the "array to string conversion" error, and my output looks like:

stdClass Object
(
    [GBP] => 10.00
    [USD] => 12.00
    [total] => Array
        (
            [GBP] => 10.00 + TAX
            [USD] => 12.00 + TAX
            [total] => Array + TAX
        )

)

I cannot figure out how to resolve the "Array to string" error, and ultimately why the "total" property is duplicated within the "total" property. I need my final output to look like:

stdClass Object
(
    [GBP] => 10.00
    [USD] => 12.00
    [total] => Array
        (
            [GBP] => 10.00 + TAX
            [USD] => 12.00 + TAX
        )

)

What have I missed? Thanks!

2
  • the object is live, as you loop over you add an array, then at some point $value will be an array 3v4l.org/gFTCh plop (array) in front of $result to cast it to an array 3v4l.org/nCSgT Commented May 12, 2022 at 15:57
  • In your foreach you are adding an array to your object, the 'total'. At some point your code will do a 'total' + TAX , thus the error. Commented May 12, 2022 at 15:57

2 Answers 2

3

You're modifying the object while you're looping over it, adding a total property. So a later iteration of the loop tries to use total as a currency and create another element in the nested total array.

Use a separate variable during the loop, then add it to the object afterward.

$totals = [];
foreach ($result as $currency => $value) {
   $currencyWithTax = $value .' + TAX';
   $totals[$currency] = $currencyWithTax;
}

$result->total = $totals;
Sign up to request clarification or add additional context in comments.

Comments

0

Your foreach is adding USD as an array

Try this

<?php

$result = new stdClass();
$result->GBP = "10.00";
$result->USD = "12.00";

foreach ($result as $currency => $value) {
   if (is_object($value) || is_array($value)) continue;
   $currencyWithTax = $value .' + TAX';
   $result->total[$currency] = $currencyWithTax;
}

print_r($result);

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.