Domanda

I am trying to solve an issue with a function stripos in PHP. We are doing promo codes and for instance, one promo code is "friends" and another is "friends40" and when someone types that in, it is saying that both of these are true so it will give them a double discount.

We need these to be distinct but not case sensitive. Is there a technique or another function we can use?

if (stripos($promo,'friends') !== false) {   
$price = $price/2;
$adddiscount = .50;
}
if (stripos($promo,'FRIENDS40') !== false) {   
$price = $price - $price * .4;
$adddiscount = .4;
}
È stato utile?

Soluzione

Both will validate as stripos is case-insensitive and friends can be found in FRIENDS40. You need to do the FRIENDS40 check first then the friends

<?php
if(stripos($promo,'FRIENDS40') !== false) {   
    $price = $price - $price * .4;
    $adddiscount = .4;
}elseif(stripos($promo,'friends') !== false) {   
    $price = $price/2;
    $adddiscount = .50;
}

An alternative would be to use strpos() which IS case-sensitive:

<?php
if(strpos($promo,'FRIENDS40') !== false) {   
    $price = $price - $price * .4;
    $adddiscount = .4;
}
if(strpos($promo,'friends') !== false) {   
    $price = $price/2;
    $adddiscount = .50;
}

To be on the safe side I would recommend using the first method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top