开发者

PHP IF statement not reacting how I think it should?

开发者 https://www.devze.com 2023-04-09 15:53 出处:网络
I am having a little trouble with the following php statement: if (!userIsLoggedIn()) { $prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice1;

I am having a little trouble with the following php statement:

if (!userIsLoggedIn()) {
    $prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice1;
} else {
    $prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice2;
}

Here is an example of two products:

product 1 -> price1 = 1.00
product 1 -> price2 = 0.00
product 2 -> price1 = 1.00
product 2 -> price2 = 0.80

If a user is not logged into our website (userIsLoggedIn function) Then they should only be able to see the product price1, regardless if product price2 exists or not.

On the other hand, When a user has logged into our website. Then they should be able to s开发者_如何学运维ee price2 for products where it exists, or they will simply see price1.

Now the problem with me code, is this:

A user is not logged on, they see price1 regardless of whether an item has a price2 set or not.

When a user has logged in, they see price2 for items that have a price two, but this is the strange part, for items that do not have a price2, it simply displays 0, Where it should display price1.

Does anyone have any input as to why the mentioned code is producing this effect?

I can provide further code relating to the userIsLoggedIn function, on request.

Thank you to anyone that would like to help!!


Your code looks fine to me. You could verify that the variables hold the value you expect by using var_dump().

Also your code might be shortened like this. However if you have to check a lot of prices it's probably not adviseable to execute userIsLoggedIn() in each check but instead save that result in a variable.

$prPrice = ($prPrice2 != 0 && userIsLoggedIn()) ? $prPrice2 : $prPrice1;


The code is working as it should - price2 for your product 1 should not return true on a call to empty() because it has a value of 0.00. Maybe you should check if a value is 0 or not instead?

0

精彩评论

暂无评论...
验证码 换一张
取 消