Home >Backend Development >PHP Tutorial >How to Explode a String into an Associative Array without Iterative Loops in PHP 5.5 ?
Exploding a String into an Associative Array without Iterative Loops
Exploding a string into an associative array without using loops can be achieved through a combination of array functions in PHP 5.5 .
Solution:
To accomplish this, we utilize the following steps:
Split the string into chunks of two elements each, alternating between key-value pairs:
<code class="php">$chunks = array_chunk(preg_split('/[-,]/', $input), 2);</code>
Extract the keys and values separately using array_column:
<code class="php">$keys = array_column($chunks, 0); $values = array_column($chunks, 1);</code>
Combine the keys and values into an associative array:
<code class="php">$result = array_combine($keys, $values);</code>
Example:
Given the input string '1-350,9-390.99', the output would be:
<code class="php">Array ( [1] => 350 [9] => 390.99 )</code>
Online Example:
You can try the code snippet at 3v4l.org.
The above is the detailed content of How to Explode a String into an Associative Array without Iterative Loops in PHP 5.5 ?. For more information, please follow other related articles on the PHP Chinese website!