1

I have a string which gets exploded into an array using the space as a delimiter. Is it possible to , for example explode the first 4 words into the array and the rest into ONE array element?

as of now the code is like this

$string = 'This is a string that needs to be split into elements';
$splitarray = explode(' ',$string);

This gives an array

 Array
    (
        [0] => This
        [1] => is
        [2] => a
        [3] => string
        [4] => that
        [5] => needs
        [6] => to
        [7] => be
        [8] => split
        [9] => into
        [10] => elements

    )

What i need is for the array to look like this

Array
    (
        [0] => This
        [1] => is
        [2] => a
        [3] => string
        [4] => that
        [5] => needs
        [6] => to be split into elements

    )

Is something like this possible?

2
  • 2
    Read the manual, explode() has a third option: array explode ( string $delimiter , string $string [, **int $limit** ] ) :) Commented Aug 7, 2013 at 8:31
  • of course the limit! Thanks :) Commented Aug 7, 2013 at 8:33

1 Answer 1

4

Use limit parameter here.

From explode() documentation:

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

Code:

$string = 'This is a string that needs to be split into elements';
$splitarray = explode(' ',$string, 7);
print_r($splitarray);

Output:

Array
(
    [0] => This
    [1] => is
    [2] => a
    [3] => string
    [4] => that
    [5] => needs
    [6] => to be split into elements
)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Cant believe I overlooked something so simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.