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

Susan Sarandon
Release: 2024-10-31 03:41:01
Original
155 people have browsed it

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],
]
Copy after login

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
);
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!