mavera2 Posted May 12, 2012 Share Posted May 12, 2012 I have an array of $fl By using values of this array, i want to create a new string. I need string size will be maximum 200 characters. When i try below code snipped, $f value is added to string two times. How can i add $f to array only one time, with checking size of string. Thank you $fl=getsomelist(); // gives an array $userList=''; foreach ($fl as $f) { if ( strlen($userList .= $f) <= (200) ) { $userList .= $f; } else { break; } } Quote Link to comment https://forums.phpfreaks.com/topic/262439-check-string-size-before-appending/ Share on other sites More sharing options...
creata.physics Posted May 12, 2012 Share Posted May 12, 2012 break; is in the wrong spot. You need break after you set the value to the variable you want to return. Here's an example: $arr = array('one', 'two', 'three', 'four', 'five'); foreach( $arr as $val ) { echo $val; break; } You'll only get the first result that way, or the first result that matches your condition. So your code would look like this: $fl=getsomelist(); // gives an array $userList=''; foreach ($fl as $f) { if ( strlen($f) <= (200) ) { $userList .= $f; break; } } Quote Link to comment https://forums.phpfreaks.com/topic/262439-check-string-size-before-appending/#findComment-1344945 Share on other sites More sharing options...
mavera2 Posted May 13, 2012 Author Share Posted May 13, 2012 Thank you for reply. But i need to check for the length of $userList .= $f not $f Quote Link to comment https://forums.phpfreaks.com/topic/262439-check-string-size-before-appending/#findComment-1345163 Share on other sites More sharing options...
Pikachu2000 Posted May 13, 2012 Share Posted May 13, 2012 In this line, you're concatenating and assigning the value at the same time with the .= operator. if ( strlen($userList .= $f) <= (200) ) { To find the strlen() before conditionally assigning the concatenated value, simply use the concatenation operator instead. if ( strlen($userList . $f) <= (200) ) { Quote Link to comment https://forums.phpfreaks.com/topic/262439-check-string-size-before-appending/#findComment-1345164 Share on other sites More sharing options...
mavera2 Posted May 13, 2012 Author Share Posted May 13, 2012 In this line, you're concatenating and assigning the value at the same time with the .= operator. if ( strlen($userList .= $f) <= (200) ) { To find the strlen() before conditionally assigning the concatenated value, simply use the concatenation operator instead. if ( strlen($userList . $f) <= (200) ) { Thank you very much. Quote Link to comment https://forums.phpfreaks.com/topic/262439-check-string-size-before-appending/#findComment-1345165 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.