selva
selva

Reputation: 31

Check if a value exists in a string of comma-separated values (PHP version of MySQL's FIND_IN_SET())

I have a variable containing comma-separated values and need to check if a given value exists as one of those values.

$a = '271,245,789';

<select name="cat" class="main" multiple="multiple">
    <option value="">--Select Category--</option>
    <?
    $cat_details = mysql_query("select category_id,category from category_tb order by category");
    while ($cat_data = @mysql_fetch_array($cat_details)) {
        ?>
        <option value="<?= $cat_data['category_id']; ?>" <? if ($a == $cat_data['category_id']) { ?> selected="selected"<? } ?>><?= $cat_data['category']; ?></option>
    <? } ?>
</select>

In MySQL, we have FIND_IN_SET() for these "," separated values. How can I do this in PHP?

Upvotes: 1

Views: 123

Answers (3)

mario
mario

Reputation: 145512

As alternative to the in_array/explode workaround you could also test with:

function find_in_set($set, $value) {
    return strstr(",$set,", ",$value,");
} 

Either way I would separate that out; your template is convoluted enough already. (You should really move the mysql_query out too, and provide a wrapper function which simply returns a list instead.)

Upvotes: 0

Tadeck
Tadeck

Reputation: 137420

You can do this like that ($key is the position of the $value within $your_string):

$key = array_search((string)$your_value, explode(',', $your_string));

See documentation for array_search() and explode().

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 132051

Something like this?

if (in_array($value, explode(',', $a)) {
  // Found
}

OK, I know now, what FIND_IN_SET() does

$index = array_search($value, explode(',', $a));

At all with explode() you can split this CSV-string into its parts and then apply every array-function on it.

Upvotes: 3

Related Questions