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...
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";
}
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()
.
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With