I have variable let says $ingredients
which contains
Flour, sugar, shortening, plant fats and oils, egg, cornstarch, cake OMath, dextrose,
whey powder, cocoa powder, lactose, whole milk powder, salt, powdered skimmed milk,
dextrin, coffee powder, butter oil, sweetened condensed skimmed milk, dried egg yolk,
leavening agent, colouring (caramel, annatto and carotene), emulsifier (soybean origin), fragrances.
Now I want to grouping its $ingredient
If $ingredients contain emulsifier and shortening, it wil shows (echo)
"Good Product"
However if there is no emulsifier and shortening, it is "Best product" (else echo "Best product"
How to code this in php ?
Thank you very much
Use in_array() to check if an item is in an array.
$ingredients = array('First ingredient', 'Second ingredient');
If the ingredients are a string separated by a comma you can convert them to an array using:
$ingredients = explode(',',$ingredients);
You may want to trim each item to ensure any whitespace around each item is removed (which will mess up your in_array() check:
$ingredientsTrimmed = array();
foreach($ingredients as $ingredient)
{
$ingredientsTrimmed[] = trim($ingredient);
}
$ingredients = $ingredientsTrimmed;
Finally, you can do your checks:
if(in_array('First ingredient',$ingredients))
{
// First ingredient is in the array
}
To check if an array contains both:
if(in_array('First ingredient',$ingredients) AND in_array('Second ingredient',$ingredients))
{
// First and second ingredient is in the array
}
To check if it contains either one or the other:
if(in_array('First ingredient',$ingredients) || in_array('Second ingredient',$ingredients))
{
// First or second ingredient is in the array
}
You can add as many 'AND's and '||'s as you need. See more about PHP's logical operators
If your ingredients are in string:
if ( strpos($ingredients, "emulsifier") === false
&& strpos($ingredients, "shortening") === false ) {
echo 'Best Product';
} elseif ( strpos($ingredients, "emulsifier") !== false
&& strpos($ingredients, "shortening") !== false ) {
echo 'Good Product';
}