bikey77
bikey77

Reputation: 6672

How to make strpos() only match whole numbers in a delimited string?

I have a comma delimited string and I need to be able to search the string for instances of a given string. I use the following function:

function isChecked($haystack, $needle) {
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return null;
    } else {
        'return 'checked="checked"';
    }
}

Example: isChecked('1,2,3,4', '2') searches if 2 is in the string and ticks the appropriate checkbox in one of my forms.

When it comes to isChecked('1,3,4,12', '2') though, instead of returning NULL it returns TRUE, as it obviously finds the character 2 within 12.

How should I use the strpos function in order to have only the correct results?

Upvotes: 2

Views: 1649

Answers (4)

user730986
user730986

Reputation: 11

function isChecked($haystack, $needle) 
{
    $pos = strpos($haystack, $needle);
    if ($pos === false)
    {
        return false;
    } 
    else 
    {
        return true;
    }
}

Upvotes: 0

Robik
Robik

Reputation: 6127

Simplest way to do it may be splitting $haystack into array and compare each element of array with $needle.

Things used [except used by you like if and function]: explode() foreach strcmp trim

Funcion:

function isInStack($haystack, $needle) 
{
    # Explode comma separated haystack
    $stack = explode(',', $haystack);

    # Loop each
    foreach($stack as $single)
    {
          # If this element is equal to $needle, $haystack contains $needle
          # You can also use strcmp:
          # if( strcmp(trim($single), $needle) )
          if(trim($single) == $needle)
            return "Founded = true";        
    }
    # If not found, return false
    return null;
}

Example:

var_dump(isInStack('14,44,56', '56'));

Returns:

 bool(true)

Example 2:

 var_dump(isInStack('14,44,56', '5'));

Returns:

 bool(false)

Hope it helps.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212442

Using explode() might be the best option, but here's an alternative:

$pos = strpos(','.$haystack.',', ','.$needle.','); 

Upvotes: 2

Emmerman
Emmerman

Reputation: 2343

function isChecked($haystack, $needle) {
    $haystack = explode(',', $haystack);
    return in_array($needle, $haystack);
}

Also you can use regular expressions

Upvotes: 5

Related Questions