复杂的`if`case,对吗?

I'm trying really hard to figure out how to solve this problem. Please be gentle, i'm still learning!

There are four workplaces named: B.Avf, R.Avf, Office and Production. Products is passing theese workplaces. Now i'm building a script that can alert if the same product is passing the same workplace twice. Now, this is the hard part: If the product has passed "B.Avf" it can't pass "R.Avf" whitout an alert, same if the product has passed "R.Avf" it can't pass "B.Avf" whitout and alert. But if the product has passed for ex. "R.Avf" it´s ok to pass "Office" whitout an alert.

This is what i got so far: (It's like example number 5 =)

Maby should i create nested ifstatements instead?

This code will turn true all times!

PHP

if($_SESSION['user']['usr_workplace'] == "R.Avf" ||
   $_SESSION['user']['usr_workplace'] == "B.Avf" && 
   strpos($history, "R.Avf") !== FALSE ||
   strpos($history, "B.Avf") !== FALSE)

Your if condition should be :

//IF this session user workplace is "B.Avf" or "R.Avf"
//AND "B.Avf" or "R.Avf" excist in history, then alert!

if(($_SESSION['user']['usr_workplace'] == "R.Avf"  || $_SESSION['user']['usr_workplace'] == "B.Avf") && (strpos($history, "R.Avf") !== FALSE || strpos($history, "B.Avf") !== FALSE))

This works, it has the right braces:

if($_SESSION['user']['usr_workplace'] == "R.Avf" || ($_SESSION['user']['usr_workplace'] == "B.Avf" && (strpos($history, "R.Avf") !== FALSE || strpos($history, "B.Avf") !== FALSE)))

It checks for r.Avf first, OR and then checks all the conditions within the braces

you should break this if into 2 methods. one should be called:

isUserSessionRBAvf($_SESSION['user']['usr_workplace'])

the other should check the strpos pos:

isHistoryAvf($history, "R.Avf")

and you would end up with just:

if(isUserSessionRBAvf(...) && isHistoryAvf(...))

this way you have a more readable code and easier to debug.

P.S. consider a different method naming

Your if statement can be made a lot simpler by removing one condition and still getting the desired result like so:

if(
    ($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf")
    && 
    strpos($history, $_SESSION['user']['usr_workplace']) !== false
)

Notice how you don't need two strpos checks, as the first part of the if statement will only allow the second part to run if it was true.

It would be better to extract this to a method or simplify it further, but for what you've asked this will do :).

what you need to do is simply check with session value to $history so you will avoid checking two strpos() where you are doing static string checking:

here you are checking with static string:

strpos($history, "R.Avf") !== FALSE ||
   strpos($history, "B.Avf") !== FALSE)

make it dynamic like this:

if($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf" && strpos($history, $_SESSION['user']['usr_workplace']) !== FALSE )