Multidimensional Array Parsing in PHP without Loops
In PHP, splitting a string into a multidimensional array without using explicit loops is possible with the judicious use of PHP's array functions.
Solution:
The following code snippet demonstrates how to transform a string in the form "A,5|B,3|C,8" into a multidimensional array without using loops:
<code class="php">$str = "A,5|B,3|C,8"; $a = array_map( function ($substr) { return explode(',', $substr); }, explode('|', $str) ); var_dump($a);</code>
Explanation:
Example Output:
array 0 => array 0 => 'A' 1 => '5' 1 => array 0 => 'B' 1 => '3' 2 => array 0 => 'C' 1 => '8'
Note:
While array_map may be faster than a manual loop in some cases, it is important to note that it still involves a loop internally. However, the abstraction provided by the functions avoids the need for explicit looping in your code.
The above is the detailed content of How can I transform a string into a multidimensional array in PHP without using loops?. For more information, please follow other related articles on the PHP Chinese website!