Home >Backend Development >PHP Problem >How to convert string array to array in php

How to convert string array to array in php

PHPz
PHPzOriginal
2023-04-20 10:11:10511browse

During the PHP development process, it is often necessary to convert strings into arrays. One of the more common ones is to convert a comma-separated string into an array. In this article, we will explain how to convert an array of strings to an array in PHP.

To convert a string array into an array, you first need to understand the structure of the string array. A string array is a string of multiple characters separated by commas. For example, the following string array:

$str = 'apple,banana,orange';

To convert $str to an array, you can use the PHP built-in function explode(). The explode() function splits a string into an array according to the given delimiter. By default, the delimiter is comma.

The following is a sample code that converts a string array to an array:

$str = 'apple,banana,orange';
$arr = explode(',', $str);
print_r($arr);

In the above code, we use the explode() function to split $str into an array and split the result Assigned to $arr. Finally, we print out the value of $arr through the print_r() function.

The output result is as follows:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

As you can see, the $arr array contains all the strings in $str, and each string is stored as an array element.

It should be noted that if $str contains spaces or other characters, it can be split by specifying the delimiter in the first parameter of the explode() function.

The above is how to convert a string array into an array. This method makes it easy to handle comma-delimited strings, and is especially useful when dealing with dynamically generated form data.

The above is the detailed content of How to convert string array to array in php. 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