Skip to content
Advertisement

Manipulate string to convert it to another string with different format

I have a string in the following form:

JavaScript

The first letter is a sort of label, the value is associated with a label.

I must manipulate and convert my string to the following:

JavaScript

With a simple loop, I created an array $temp:

JavaScript

Starting from here, I could eventually loop again to build my new string. Or maybe I could do it even in one loop.

But, is there anything better I could do? I checked the capabilities of array_map, array_filter and array_walk but I could not find a way to apply them in this particular case.

Thanks in advance.

Advertisement

Answer

A couple of coding improvements would reduce some of the code, using a foreach instead of the for (where you also have to count the items). Also inside the loop, use explode() once to reduce repetition of the code.

This also inside the loop checks if the key is already present. If it is, it just appends the new value, if it isn’t it creates a new value with the key and value. When it outputs the value, it uses implode() to stick the values back together…

JavaScript

gives…

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