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