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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 06:25:30926browse

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:

  1. 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>
  2. Extract the keys and values separately using array_column:

    <code class="php">$keys = array_column($chunks, 0);
    $values = array_column($chunks, 1);</code>
  3. 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!

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