Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in comma separated string with PHP [duplicate]

Tags:

php

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

like image 305
kuttypraba Avatar asked Nov 24 '12 07:11

kuttypraba


4 Answers

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";
}
like image 67
Decent Dabbler Avatar answered Nov 17 '22 13:11

Decent Dabbler


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().

like image 36
Brad Avatar answered Nov 17 '22 12:11

Brad


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";
like image 39
Tapas Pal Avatar answered Nov 17 '22 12:11

Tapas Pal


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.

like image 42
phant0m Avatar answered Nov 17 '22 14:11

phant0m