"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert a String to an Associative Array Using Array Functions?

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

Published on 2024-11-07
Browse:500

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:

$input  = '1-350,9-390.99';

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

Output:

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

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

Release Statement This article is reprinted at: 1729549336 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3