Home >Backend Development >PHP Tutorial >How to Split a String into a Multidimensional Array in PHP Without Explicit Loops?
Splitting a String into a Multidimensional Array in PHP Without Loops
To split a string into a multidimensional array in PHP without relying on iterative structures, a combination of array functions can be employed to achieve the desired result. Consider a string in the format "A,5|B,3|C,8" as an example.
Utilizing array_map and explode, you can accomplish this task efficiently. For instance, in PHP 5.3 and above, the following code snippet can be used:
<code class="php">$str = "A,5|B,3|C,8"; $a = array_map( function ($substr) { return explode(',', $substr); }, explode('|', $str) ); var_dump($a);</code>
This code snippet begins by splitting the input string into an array of substrings using the explode function, which separates the string at the pipe character. Then, array_map is employed to apply the explode function to each substring, further splitting it into an array of two elements: the first element containing the letter and the second element containing the number.
The result is a multidimensional array where each inner array corresponds to a single pair of letter and number from the input string:
array 0 => array 0 => string 'A' (length=1) 1 => string '5' (length=1) 1 => array 0 => string 'B' (length=1) 1 => string '3' (length=1) 2 => array 0 => string 'C' (length=1) 1 => string '8' (length=1)
While this solution eliminates explicit looping in the user's code, it is important to note that internally, array_map still employs a loop to iterate over the input array. Therefore, the absence of a loop in the presented code does not imply the absence of looping altogether.
The above is the detailed content of How to Split a String into a Multidimensional Array in PHP Without Explicit Loops?. For more information, please follow other related articles on the PHP Chinese website!