Home  >  Article  >  Backend Development  >  How to Efficiently Explode a String into an Associative Array without Loops in PHP?

How to Efficiently Explode a String into an Associative Array without Loops in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 06:29:30804browse

How to Efficiently Explode a String into an Associative Array without Loops in PHP?

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

  1. Array_chunk: Divides the input string into chunks of pairs.
  2. Array_column: Extracts the keys and values from the chunks into separate arrays.
  3. Array_combine: Creates an associative array by combining the keys and values.

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!

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