I'm trying to build up a php if statement with or "||" operators but doesn't seems to work
$country_code ="example_country_code";
if ( $country_code != 'example_country_code' || !clientIscrawler()) {
echo 'the script can be executed';
}
else {
echo 'skipping';
}
with the given example should be echoed skipping but doesn't happening like that. What I'm doing wrong?
Perhaps the double negatives is giving you problems, let's rewrite it to:
!($country_code == 'example_country_code') || !clientIscrawler()
This can be turned into an equivalent condition with &&
:
!($country_code == 'example_country_code' && clientIscrawler())
By reversing the if
you would get this:
if ($country_code == 'example_country_code' && clientIscrawler()) {
echo 'skipping';
} else {
echo 'the script can be executed';
}
Therefore, in your code, it will only print skipping if clientIscrawler()
is truthy.
Try this way:
if ( ($country_code != 'example_country_code') || !clientIscrawler()) { ...
In your given code, it all depends on your function call
!clientIscrawler()
You will be getting the script can be executed
output only when your function call returns FALSE
. I think it is returning TRUE
right now, which is why you are not getting the desired output.
Maybe this can help you:
if ( ($country_code != 'example_country_code') || clientIscrawler() == false) {
If you have multiple conditions with OR operator in which case you don't want the if statement to evaluate as true, the syntax is:
if(!($something == "something" || $something == 'somethingelse')){
do stuff...
}
here an example:
$apples = array (
1 => "Pink Lady",
2 => "Granny Smith",
3 => "Macintosh",
4 => "Breaburn"
);
foreach($apples as $apple){
// You don't wanna echo out if apple name is "Pink Lady" or "Macintosh"
if(!($apple == "Pink Lady" || $apple == "Macintosh")){
echo $apple."<br />";
}
}
// Output is:
Granny Smith
Breaburn