abstrakone Posted September 25, 2009 Share Posted September 25, 2009 I'm looking for a way to do the following. I have a list of words of various char lengths. I have a limited number of chars I can use in a given strings size. I'd like to organize the words to fit as many of them as I can in a given string without going over the limit or cutting any of the words off. Bobby Sally Joe Sue Mark Eric Jason Billy Michael Jeremy Jacob ... etc I have a limit of 140 characters to fit them all in, including spaces. If I have more names than space avail in that string, I'd like to generate another string using the same function as described above until all the names in the list are used. Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/175547-organize-words-so-you-can-fit-the-most-number-of-words-in-a-given-length/ Share on other sites More sharing options...
DavidAM Posted September 25, 2009 Share Posted September 25, 2009 maybe something like: $names = array('Bobby', 'Sally', 'Joe', 'Sue', 'Mark', 'Eric', 'Jason', 'Billy', 'Michael', 'Jeremy', 'Jacob'); $maxLen = 140; $list = array(); $line = ''; foreach ($names as $name) { if ((strlen($line) + strlen($name) + 1) > $maxLen) { // +1 for the space $list[] = $line; $line = ''; } $line .= (strlen($line)>0 ? ' ' : '') . $name; } if (strlen($line) > 0) $list[] = $line; // pickup the last line Quote Link to comment https://forums.phpfreaks.com/topic/175547-organize-words-so-you-can-fit-the-most-number-of-words-in-a-given-length/#findComment-925058 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.