Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP, How can I split a string into 2 arrays?

I have a string that looks like this…
333333-000000,555555-444444,888888-111111

I can use explode to get everything into an array using the commas as a delimiter, but then I’d have to explode each again using the – as a delimiter. Is there an easier way? I want the end result like this…

a[0]=333333 b[0]=000000

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a[1]=555555 b[1]=444444

a[2]=888888 b[2]=111111

>Solution :

Yes, there is an easier way to achieve the desired result without having to use multiple explode functions. You can use the list() and explode() functions in combination to achieve the desired result.

Here is an example code snippet that shows how to do this:

$string = "333333-000000,555555-444444,888888-111111";
$array = explode(",", $string);

foreach ($array as $key => $value) {
    list($a[$key], $b[$key]) = explode("-", $value);
}

// Output the result
print_r($a);
print_r($b);

The explode() function is used to split the original string into an array using the comma delimiter. Then, a foreach loop is used to iterate through the array and split each element using the hyphen delimiter. The list() function is used to assign the values to separate variables.

The result is stored in two separate arrays $a and $b. The print_r() function is used to output the arrays and their contents.

This will give you the desired result:

Array
(
    [0] => 333333
    [1] => 555555
    [2] => 888888
)

Array
(
    [0] => 000000
    [1] => 444444
    [2] => 111111
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading