In PHP, we often need to convert strings into associative arrays for data manipulation and processing. This article will introduce several methods to convert PHP strings into associative arrays.
- Use the explode() function
The explode() function splits the string into an array, and the delimiter and string can be passed in as parameters. We can use this function to split the string into the form of $key=>$value, as shown below:
$str = "name=John&age=25&city=NewYork"; // 分割字符串 $arr1 = explode("&", $str); foreach($arr1 as $val){ $arr2 = explode("=", $val); $result[$arr2[0]] = $arr2[1]; } print_r($result);
The output result is:
Array ( [name] => John [age] => 25 [city] => NewYork )
- Use the parse_str() function
The parse_str() function parses a string into a variable and assigns its value to an array, passing in the form $key=>$value as a parameter. The following is an example of using the parse_str() function:
$str = "name=John&age=25&city=NewYork"; parse_str($str,$result); print_r($result);
The output result is:
Array ( [name] => John [age] => 25 [city] => NewYork )
- Using regular expressions
We can use regular expressions Formula to match a string and then store the result in an associative array. The following is an example of using the preg_match_all() function:
$str = "name=John&age=25&city=NewYork"; preg_match_all('/([^&=]+)=([^&]*)/', $str, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $result[$match[1]] = $match[2]; } print_r($result);
The output result is:
Array ( [name] => John [age] => 25 [city] => NewYork )
Summary
This article introduces three ways to convert PHP strings into associative arrays method. Use these methods to quickly convert strings into arrays and perform data processing and operations. In actual development, we can choose different methods for string conversion according to needs.
The above is the detailed content of How to convert php string into associative array. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
