Skip to content
Advertisement

PHP Explode Populate Keys Not Values

Let’s say you have a comma-delimited string:

JavaScript

Calling explode(',', $str); will return the following:

JavaScript

Is there a way to explode such that the resulting array’s keys, and not values, are populated? Something like this:

JavaScript

Advertisement

Answer

You can use array_fill_keys to use the output of explode as keys to a new array with a given value:

JavaScript

Output:

JavaScript

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement