Home  >  Article  >  Backend Development  >  How to Efficiently Split a String into a Multidimensional Array in PHP Without Loops?

How to Efficiently Split a String into a Multidimensional Array in PHP Without Loops?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 03:41:01156browse

How to Efficiently Split a String into a Multidimensional Array in PHP Without Loops?

String Manipulation: Efficiently Splitting a String into a Multidimensional Array

Splitting a string into a multidimensional array is a common task in programming. Traditional approaches often rely on iterative loops to achieve this. However, PHP offers an efficient loopless solution.

For strings like "A,5|B,3|C,8," the task is to transform them into a multidimensional array such as:

[
    ['A', 5],
    ['B', 3],
    ['C', 8],
]

The solution involves combining the power of explode() and array_map(). Here's how it works:

<code class="php"><?php
$str = "A,5|B,3|C,8";

// Split the string into individual parts based on the pipe symbol
$parts = explode('|', $str);

// Use array_map() to transform each part into an array
$a = array_map(
    function ($substr) {
        // Explode each part again to separate the values
        return explode(',', $substr);
    },
    $parts
);

By combining array_map() and explode(), the loop over the individual parts is encapsulated within the built-in functions, eliminating the need for explicit looping in your code.

The resulting $a array will be the desired multidimensional array, with each element representing a part of the original string split into an array of its own:

var_dump($a);

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)</code>

The above is the detailed content of How to Efficiently Split a String into a Multidimensional Array in PHP Without Loops?. 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