0

I have the following array:

array (size=5)
  50 => string 'Automative Repair' (length=17)
  44 => string 'Baker' (length=5)
  47 => string 'Barber' (length=6)
  51 => string 'Bicycle Rentals' (length=15)
  52 => string 'Car Detailing' (length=13)

I need to convert the key from integer to a string (in my foreach loop), so it shows as a string instead, like 50 would be '50' (associative array) as follows:

array (size=5)
  '50' => string 'Automative Repair' (length=17)
  '44' => string 'Baker' (length=5)
  '47' => string 'Barber' (length=6)
  '51' => string 'Bicycle Rentals' (length=15)
  '52' => string 'Car Detailing' (length=13)

I have tried the following PHP foreach loop, creating a new array $categories_new_format, by casting a (string) on the term_id as it loops, but it doesn't do it:

    foreach ( $categories as $category ) {
        $categories_new_format[(string)$category->term_id] = $category->name;
    }
Mario
  • 177
  • 1
  • 12
  • It clearly states in the official PHP documentation that `'1' => 'foo'` will become `1 => 'foo'` and is accessible either way – Jaquarh Jun 26 '22 at 13:59
  • @Jaquarh Yeah I get that, but I need a solution, because the 3rd party plugin I'm delivering the array contents to, expects a `string` type, so I get a `Warning: rtrim() expects parameter 1 to be string`. – Mario Jun 26 '22 at 14:08

0 Answers0