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
https://forums.phpfreaks.com/topic/262439-check-string-size-before-appending/
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;
    }
}

 

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.