Jump to content

Check string size before appending


mavera2

Recommended Posts

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;
    }
}

Link to comment
Share on other sites

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;
    }
}

 

Link to comment
Share on other sites

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) ) {

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.