How to Convert a String to an Associative Array Using Array Functions?

DDD
Release: 2024-10-22 06:24:03
Original
757 people have browsed it

How to Convert a String to an Associative Array Using Array Functions?

Convert String to Associative Array with Array Functions

In PHP, the need often arises to transform a string containing key-value pairs into an associative array. Consider a string like "1-350,9-390.99", where each element is separated by a hyphen and comma. The goal is to create an associative array where the first number in each element becomes the key, and the second number becomes the value.

Achieving this conversion can be done efficiently using PHP's built-in array functions. The first step involves splitting the string into individual arrays using preg_split("/[-,]/", $input), which separates the numbers by hyphens and commas. The result is a list of sub-arrays, each containing a key and a value.

Next, we use array_chunk to group these sub-arrays into chunks of two, ensuring one element holds the key and the other holds the value. Finally, array_column is employed to extract the keys and values into separate arrays. Using array_combine on these arrays yields the desired associative array.

Code Snippet:

<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));</code>
Copy after login

Output:

Array
(
    [1] => 350
    [9] => 390.99
)
Copy after login

This method effectively converts the string into an associative array without resorting to loops, showcasing the power of PHP's array functions.

The above is the detailed content of How to Convert a String to an Associative Array Using Array Functions?. 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
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!