12

I need to check if my id exists in comma separated string.

My string is saved as "1,2,3,4,10" in database.

I have tried

$HiddenProducts = array($sqlvalue);

if (in_array(2, $HiddenProducts)) {
  echo "Available";
} else {
  echo "Not available";
}

It is not working. Any solutions please...

Michiel Roos
  • 863
  • 11
  • 13
kuttypraba
  • 129
  • 1
  • 1
  • 3
  • To make an array out of a string with comma separated values you need `explode()` instead of `array()`. – Ja͢ck Nov 24 '12 at 07:08
  • Why don't you use your database function to check it? And why is it stored as a string? – meze Nov 24 '12 at 08:50
  • The fasetest way to ckeck if a value is inside a CSV is: `strpos(',' . $list . ',', ',' . $item . ',') !== FALSE;` – Michiel Roos Feb 25 '14 at 07:09

4 Answers4

47

Use explode() to create an array of string parts from a string, by splitting it by a certain delimiter (in this case a comma).

$HiddenProducts = explode(',',$sqlvalue);
if (in_array(2, $HiddenProducts)) {
  echo "Available";
} else {
  echo "Not available";
}
Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
4

in_array() is in fact what you want, but you are creating your array incorrectly.

Assuming $sqlvalue = '1,2,3,4,10'...

$hiddenProducts = explode(',', $sqlvalue);

Then you can use in_array().

Brad
  • 159,648
  • 54
  • 349
  • 530
1

first using explode function convert the comma-separated string in to array

$HiddenProducts = explode(',',$sqlvalue);

then use in_array function to check

 if (in_array(2, $HiddenProducts))
   echo "Available";
else
   echo "Not available";
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86
1

Instead of merely curing the symptom, let me offer a different approach.

You should probably not store your information in the table like that. It should be possible to let the database figure out, if some product is hidden or not. For that, you need to normalize your data properly.

Apparently, you have a table of products somewhere and some should be hidden. If this is a property true or false that belongs to every product, you can just add it to the your products table as a new column.

SELECT id FROM products WHERE id = 2 AND hidden = 1

If hidden is not an intrinsic property of your products, you can also create a helper table that is simply a list of product IDs.

An entry simply says that the product is hidden. If an ID is absent from the table, it's not hidden.

phant0m
  • 16,595
  • 5
  • 50
  • 82