Home > Article > Backend Development > How to force convert string to array in php
In PHP, converting a string to an array is a common operation. There are several ways to coerce a string into an array. In this article, we will discuss these methods and show you how to correctly convert a string to an array.
The explode function can split a string into an array according to the specified delimiter. An example is as follows:
$str = 'apple,banana,orange'; $arr = explode(',', $str); print_r($arr);
The output is:
Array ( [0] => apple [1] => banana [2] => orange )
In the above example, we use the explode function to comma-separate the string into array elements.
The str_split function can split a string into an array according to the specified length. An example is as follows:
$str = 'apple'; $arr = str_split($str); print_r($arr);
The output is:
Array ( [0] => a [1] => p [2] => p [3] => l [4] => e )
In the above example, we split the string into individual characters, and each character is an element of the array.
The preg_split function can split a string into array elements according to a regular expression. The example is as follows:
$str = 'apple,banana.orange'; $arr = preg_split('/[,\.]/', $str); print_r($arr);
The output result is:
Array ( [0] => apple [1] => banana [2] => orange )
In the above example, we use the preg_split function to split the string into array elements according to commas or periods.
If you want to split the string into array elements according to the specified length, but you cannot use the str_split function, you can use the foreach loop to process. The example is as follows:
$str = 'apple'; $arr = array(); for ($i = 0; $i < strlen($str); $i++) { $arr[] = $str[$i]; } print_r($arr);
The output result is:
Array ( [0] => a [1] => p [2] => p [3] => l [4] => e )
In the above example, we implement string to array conversion by looping to add each character of the string to an empty array .
In PHP, you can use the cast operator to cast a variable to an array type. An example is as follows:
$str = 'apple'; $arr = (array) $str; print_r($arr);
The output is:
Array ( [0] => apple )
In the above example, we use the cast operator to cast the string to an array type. It should be noted that this method can only convert a string into a single-element array.
Summary
In PHP, there are several ways to convert a string to an array, including using the explode function, str_split function, preg_split function, loops, and cast operator. According to the specific scenario, choose the appropriate method to convert string to array. It should be noted that when converting a string into an array, factors such as the structure and data type of the array need to be considered to avoid errors and exceptions.
The above is the detailed content of How to force convert string to array in php. For more information, please follow other related articles on the PHP Chinese website!