Search code examples
phpif-statementcomparison

PHP If variable = a and not = b


php 7.3.18

mysql 5.7.30

Here is the relevant code, which fails immediately so I would appreciate it being corrected.

The first 'if' is ok, but the issue is with the 2nd + 3rd.

$targetcatid2, $targetcatid3, $targetweight2, $targetweight3 have been properly declared.

The object is that if a product is in Category2 and not in Category3 then the weight will become Weight2 and vice-a-versa.

$row2=mysqli_fetch_array($select2);

if($row2['category_id']== $targetcatid){
    $row['product_weight']= $targetweight;
}

if($row2['category_id']== $targetcatid2 && !== $targetcatid3){
    $row['product_weight']= $targetweight2;
}

if($row2['category_id']== $targetcatid3 && !== $targetcatid2){
    $row['product_weight']= $targetweight3;
}

My latest effort is:

if($row2['category_id']== $targetcatid){ $row['product_weight']= $targetweight; }

if($row2['category_id']== $targetcatid2 && $row2['category_id']!== $targetcatid3){ $row['product_weight']= $targetweight2; }

elseif($row2['category_id']== $targetcatid3 && $row2['category_id']!== $targetcatid2){ $row['product_weight']= $targetweight3; }

elseif($row2['category_id']== $targetcatid2 && $row2['category_id']== $targetcatid3){ $row['product_weight']= $targetweight3; }

I have found that the new condition does not work, even on its own. But do not understand why:

elseif($row2['category_id'] == $targetcatid2 && $row2['category_id'] == $targetcatid3){ $row['product_weight'] = $targetweight3; }


Solution

  • You are not understanding the && operator correctly.

    Instead of this

    if($row2['category_id']== $targetcatid2 && !== $targetcatid3){
    

    You should separately compare the conditions.

    if($row2['category_id']== $targetcatid2 && $row2['category_id'] !== $targetcatid3){