I have a string in the following form:
$my_original_string = "A value1,A value2,E value3,A value4";
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:
$my_converted_string = "A: value1 value2 value4, E: value3";
With a simple loop, I created an array $temp:
$my_original_string = "A value1,A value2,E value3,A value4"; $original_string_to_array = explode(",", $my_original_string); $o_len = count($original_string_to_array); $temp = []; for($i=0; $i<$o_len; $i++){ $temp[explode(" ",$original_string_to_array[$i])[0]][] = explode(" ",$original_string_to_array[$i])[1]; } print_r($temp); /* Result: Array ( [A] => Array ( [0] => value1 [1] => value2 [2] => value4 ) [E] => Array ( [0] => value3 ) ) */
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…
$my_original_string = "A value1,A value2,E value3,A value4"; $originalArray = explode(",", $my_original_string); $output = []; foreach($originalArray as $item ) { [$key, $value] = explode(" ", $item, 2); $output[$key] = (isset($output[$key])) ? $output[$key]." ".$value : "$key: $value"; } print_r(implode(", ", $output));
gives…
A: value1 value2 value4, E: value3