Efficient String Exploding to Associative Array
Exploding a string into an associative array is a common task in programming. This question explores a method to achieve this efficiently without resorting to loops.
Challenge
Given a string containing comma-separated pairs of values (e.g., "1-350,9-390.99"), the goal is to transform it into an associative array where the first value becomes the key and the second value becomes the associated value.
Answer
Leveraging the power of PHP array functions, it is possible to perform this transformation in just two lines:
<code class="php">$chunks = array_chunk(preg_split('/[-,]/', $input), 2); $result = array_combine(array_column($chunks, 0), array_column($chunks, 1));</code>
Explanation
This method efficiently separates the keys and values and combines them into the desired associative array without the need for iterative processing.
The above is the detailed content of How to Efficiently Explode a String into an Associative Array without Loops in PHP?. For more information, please follow other related articles on the PHP Chinese website!