如何使用IF ELSE比较php中的数据

时间:2014-01-26 13:34:24

标签: php html

我有变量let $ingredients包含

面粉,糖,起酥油,植物油脂,鸡蛋,玉米淀粉,蛋糕OMath,葡萄糖,

乳清粉,可可粉,乳糖,全脂奶粉,盐,脱脂奶粉,

糊精,咖啡粉,黄油,甜味浓缩脱脂牛奶,干蛋黄,

发酵剂,着色剂(焦糖,胭脂红和胡萝卜素),乳化剂(大豆来源),香料。

现在我想对其$ingredient

进行分组
  1. 如果$成分含有乳化剂和起酥油,它会显示(echo)“好产品”

  2. 但如果没有乳化剂和起酥油,则为“最佳产品”(else echo "Best product"

  3. 如何在php中编写代码?

    非常感谢

2 个答案:

答案 0 :(得分:2)

使用in_array()检查项目是否在数组中。

$ingredients = array('First ingredient', 'Second ingredient');

如果成分是用逗号分隔的字符串,则可以使用以下命令将它们转换为数组:

$ingredients = explode(',',$ingredients);

您可能希望修剪每个项目以确保删除每个项目周围的任何空格(这会弄乱您的in_array()检查:

$ingredientsTrimmed = array();

foreach($ingredients as $ingredient)
{
    $ingredientsTrimmed[] = trim($ingredient);
}

$ingredients = $ingredientsTrimmed;

最后,您可以进行检查:

if(in_array('First ingredient',$ingredients))
{
    // First ingredient is in the array
}

检查数组是否包含:

if(in_array('First ingredient',$ingredients) AND in_array('Second ingredient',$ingredients))
{
    // First and second ingredient is in the array
}

检查它是否包含其中一个:

if(in_array('First ingredient',$ingredients) || in_array('Second ingredient',$ingredients))
{
    // First or second ingredient is in the array
}

您可以根据需要添加任意数量的“AND”和“||”。 See more about PHP's logical operators

答案 1 :(得分:0)

如果你的成分是字符串:

if ( strpos($ingredients, "emulsifier") === false
  && strpos($ingredients, "shortening") === false ) {
   echo 'Best Product';
} elseif ( strpos($ingredients, "emulsifier") !== false
  && strpos($ingredients, "shortening") !== false ) {
   echo 'Good Product';
}