0

I have an array with string with certain lenght of characters:

Array
(
    [0] => 

foo

[1] =>

bar

[2] =>

hello

[3] =>

world

[4] =>

i

[5] =>

great

)

I need to combine those values into chunks until some string length limit is reached.

For example max char number is 6

So new array would look like this

Array
(
    [0] => foobar
    [1] =>  hello
    [2] => worldi
    [3] => great
)

"Foo" and "Bar", "i" and "world" merges, because it does not exceed 6 max allowed char limit. However "Hello" don't because combined char limit exceeds 6.

Can't wrap my head around how to do it.

2 Answers 2

2

Easy:

$arr = array('foo','bar','hello', 'world', 'i', 'great');
$limit = 6;
$result = array(''); // some hack
$cur_key = 0;        // some hack
foreach ($arr as $word) {
    if (strlen($result[$cur_key]) + strlen($word) <= $limit) {
        $result[$cur_key] .= $word;
    } else {
        $result[] = $word;
        $cur_key++;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

array functions exist for a reason.
What array function? For what reason?
you are doing it manually using a foreach, strlen and an if. implode and str_split are your friends.
Your function even doesn't do what OP wants.
it's not "my" function. it's php's. and you should try it again.
0

Pretty straightforward:

// YOUR ARRAY
$array = array('foo', 'bar', 'hello', 'world', 'i', 'great');

// STRING CONTAINING YOUR ARRAY VALUES CONCATENATED
$alltogheter = implode("", $array);

// NEW ARRAY FROM YOUR STRING (SPLIT BY 6 CHARS)
$newarray = str_split($alltogheter, 6);

8 Comments

Result of your function: array(4) { [0]=> string(6) "foobar" [1]=> string(6) "hellow" [2]=> string(6) "orldig" [3]=> string(4) "reat" }
exactly. I don't see any whitespaces in OP's array.
OP wants [1] => hello [2] => worldi You give him: [1]=> string(6) "hellow" [2]=> string(6) "orldig".
Do you even understand that your code return results that's not like OP wants?
yes I can read: I need to combine those values into chunks until some string length limit is reached. For example max char number is 6
|

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.