Home > Mobile >  PHP Array to String Conversion When Adding Strings in Foreach
PHP Array to String Conversion When Adding Strings in Foreach

Time:05-13

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!

CodePudding user response:

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;

CodePudding user response:

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);
  • Related