Search code examples
phparraysstringscripting

PHP - Loopless way to split a string into a multidimensional array


How do I split a string into a multidimensional array in PHP without loops?

My string is in the format "A,5|B,3|C,8"


Solution

  • Without you actually doing the looping part, something based on array_map + explode should do the trick ; for instance, considering you are using PHP 5.3 :

    $str = "A,5|B,3|C,8";
    
    $a = array_map(
        function ($substr) {
            return explode(',', $substr);
        }, 
        explode('|', $str)
    );
    var_dump($a);
    

    Will get you :

    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)
    

    Of course, this portion of code could be re-written to not use a lambda-function, and work with PHP < 5.3 -- but not as fun ^^


    Still, I presume array_map will loop over each element of the array returned by explode... So, even if the loop is not in your code, there will still be one...