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;
    }
2
  • It clearly states in the official PHP documentation that '1' => 'foo' will become 1 => 'foo' and is accessible either way Commented Jun 26, 2022 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. Commented Jun 26, 2022 at 14:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.