BGPHiJACK
BGPHiJACK

Reputation: 1397

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

$string = "1-2-3-4 5-6-7-8";

'-' = Separates Values

' ' = New array

$array1 = explode("-", $string, 4);

I have this code so far which will do values 1 to 4 but I want it to stop at 4 and create a new set.

Ex.


$SET_1[0] = 1
$SET_1[1] = 2
$SET_1[2] = 3
$SET_1[3] = 4

Then

$SET_2[0] = 5
$SET_2[1] = 6
$SET_2[2] = 7
$SET_2[3] = 8

Any suggestions would be appreciated, also how would I reverse this after I have put them into arrays?

Upvotes: 1

Views: 330

Answers (3)

Yanick Rochon
Yanick Rochon

Reputation: 53626

Use array_chunk

$string = "1-2-3-4-5-6-7-8";
$data = array_chunk(explode('-', $string), 4);

which will return

$data = array(
   array('1', '2', '3', '4'),
   array('4', '5', '6', '7')
);

** UPDATE **

This will create an array of arrays containing each at most 4 elements. If you need variable size arrays, specified by ' ' in your string, use this instead :

$string2 = "1-2-3-4 5-6-7-8-9-10";

function inner_split(&$items) {
    $items = explode('-', $items);
}
$data2 = explode(' ', $string2);
array_walk($data2, 'inner_split');

var_dump($data2);

which will output

$data2 = array(
   array('1', '2', '3', '4'),
   array('5', '6', '7', '8', '9', '10')
);

Upvotes: 5

Jesse Cohen
Jesse Cohen

Reputation: 4040

what you want are multidimensional arrays:

so something like

 $set[i] = explode('-',$string, 4)

then just nest this in a loop and iterate over the string, you'll be able to access each individual character as

 $set[i][j]

where i is the set index and j is 1,2,3 or 4

Upvotes: 0

user613857
user613857

Reputation:

First split with whitespace into chunks of number sets, then split the numbers with "-" into arrays. You'll need to split the whitespace using Regex.

You should use preg_split(regex, string) and the whitespace character is \s in Regex. So something like preg_split('/\s/', $string).

Upvotes: 0

Related Questions