Split a string with two delimiters into two arrays (explode twice)

You can explode the string by commas, and then explode each of those values by x, inserting the result values from that into the two arrays:

$str = "20x9999,24x65,40x5";

$array1 = array();
$array2 = array();
foreach (explode(',', $str) as $key => $xy) {
    list($array1[$key], $array2[$key]) = explode('x', $xy);
}

Alternatively, you can use preg_match_all, matching against the digits either side of the x:

preg_match_all('/(\d+)x(\d+)/', $str, $matches);
$array1 = $matches[1];
$array2 = $matches[2];

In both cases the output is:

Array
(
    [0] => 20
    [1] => 24
    [2] => 40
)
Array
(
    [0] => 9999
    [1] => 65
    [2] => 5
)

Note that as of PHP7.1, you can use array destructuring instead of list, so you can just write

[$array1[$key], $array2[$key]] = explode('x', $xy);

instead of

list($array1[$key], $array2[$key]) = explode('x', $xy);

You can use this to simplify the assignment of the result from preg_match_all as well:

[, $array1, $array2] = $matches;

Demo on 3v4l.org

Leave a Comment