Home  >  Article  >  Backend Development  >  How to Convert a Delimited String to an Associative Array without Loops?

How to Convert a Delimited String to an Associative Array without Loops?

DDD
DDDOriginal
2024-10-22 06:27:03983browse

How to Convert a Delimited String to an Associative Array without Loops?

Converting a Delimited String to an Associative Array without Loops

The task at hand is to transform a string containing key-value pairs separated by delimiters (e.g., "1-350,9-390.99") into an associative array. While loops can accomplish this, it is possible to achieve this using only array functions.

One approach involves utilizing the array_chunk function to break the string into chunks of two elements: the key and value. This is followed by array_column to extract the keys and values into separate arrays. Finally, array_combine is used to combine these extracted arrays into the desired associative array.

Here's a PHP 5.5 implementation:

<code class="php">$input  = '1-350,9-390.99';

$chunks = array_chunk(preg_split('/[-,]/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));

print_r($result);</code>

This will produce the following associative array:

Array
(
    [1] => 350
    [9] => 390.99
)

This approach not only eliminates the need for explicit loops but also utilizes native PHP functions for enhanced performance and code readability.

The above is the detailed content of How to Convert a Delimited String to an Associative Array without Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn