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

Barbara Streisand
Release: 2024-10-22 06:25:30
Original
925 people have browsed it

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

    <code class="php">$keys = array_column($chunks, 0);
    $values = array_column($chunks, 1);</code>
    Copy after login
  3. Combine the keys and values into an associative array:

    <code class="php">$result = array_combine($keys, $values);</code>
    Copy after login

Example:

Given the input string '1-350,9-390.99', the output would be:

<code class="php">Array
(
    [1] => 350
    [9] => 390.99
)</code>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!