How do i add another condition to the same snippet below? I need to add a "OR" condition where $variable = $variable?
if ( stripos($userallowed, $sid) !== false ) {
echo("allowed");
} else {
echo("not allowed");
die();
}
if ( stripos($userallowed, $sid) !== false OR $variable == $variable )
Related
I am curling on a specific page that returns only html. To determine what page it returns, I simply try to stripos the result of the curl
Like so:
$result = curl_exec($ch);
if(stripos($result, 'success') !== false) {
// do something
} else {
if (stripos($result, 'foo') !== false) {
// do something
} else if (stripos($result, 'foo') !== false) {
// do something
} else if (stripos($result, 'bar') !== false) {
// do something
} else if (stripos($result, 'bazz') !== false) {
// do something
} else {
// do something
}
}
This is quite messy I think, is there an OO way or functional way to solve this kind of problem if I were looking at minimal if statements or ultimately an if-less code.
What you are searching for a ways of abstraction. In this example you are repeating yourself in case analysis and this might be the best approach if the "do something" is very different and not consistent.
$map = [ 'success' => function () { return 1; },
'foo' => function () { return 2; },
'bar' => function () { return 3; },
'bazz' => function () { return 4; } ];
foreach ( $map as $search => $value )
{
if (stripos($result, $search) !== false )
{
return call_user_func($value);
}
}
In my example these could just have been constants and we could just return them instead of applying a function. In a functional pattern this would be like the function any in Scheme SRFI-1 except it returns it's true value:
// This function uses PHP 5.6 ellipsis
function array_any(callable $callable, ...$arrays) {
if( count($arrays) == 1 ) {
$args_zipped = array_map( function ($x) { return [$x]; }, $arrays[0]);
} else {
array_unshift( $arrays, null);
$args_zipped = call_user_func_array( "array_map", $arrays);
}
foreach ( $args_zipped as $args ) {
$result = call_user_func_array($callable, $args);
if( $result !== false )
return $result;
}
return false;
}
array_any( function ($search, $value) {
if ( stripos($result, $search) !== false )
return $value;
return false;
},
array_keys($map),
array_values($map));
The function in itself uses linear update, but as you can see it works similar to array_map.
This simple function would do that work:
function checkWord ($haystack,$needle){
foreach ($needle as $word) {
if (stripos($haystack, $word) !== false) {
echo $word." was found!<br/>";
}
else{
echo $word." wasn't found<br/>";
}
}
}
checkWord("Hello what's up?",array('Hello','Huhud','up','?'));
This will output:-
Hello was found!
Huhud wasn't found
up was found!
? was found!
This question already has answers here:
switch statement with two variables at a time
(6 answers)
Closed 8 years ago.
How do I convert the below to a switch instead of If/Else? I read that if I have more than if/elseif/else that i should use a switch instead
$domain = ($_SERVER['HTTP_HOST']);
if ($_SERVER['HTTP_HOST']=="domain1.com" && strpos($_SERVER['REQUEST_URI'], 'ab03') !== false ) {
codeblock();
$tlink = "http://google.com";
} elseif ($_SERVER['HTTP_HOST']=="domain1.com" && strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
$tlink = "http://cnn.com";
} elseif ($_SERVER['HTTP_HOST']=="domain2.com" && strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
$tlink = "http://yahoo.com";
} elseif ($_SERVER['HTTP_HOST']=="domain3.com" && strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
$tlink = "http://example.com";
} else {
$tlink = "http://cbs.com";
}
You could have found this yourself in a 5 sec Google search...
switch($i){
case 0:
break;
}
Simply replace $i with $_SERVER['HTTP_HOST'] to compare and 0 with the wanted value example domain1.com.
http://php.net/manual/en/control-structures.switch.php
However the switch is not really adapted to your code as you have multiple conditions in your if. Since the second condition seems to be always the same, you could simply put the switch in the if of the second condition or use the clause inside each case but this would be redundant code.
try use code
switch ($domain) {
case 'domain1.com':
if(strpos($_SERVER['REQUEST_URI'], 'ab03') !== false) {
codeblock();
$tlink = "http://google.com";
} elseif(strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
$tlink = "http://cnn.com";
}
break;
case 'domain2.com':
if(strpos($_SERVER['REQUEST_URI'], 'ab05') !== false) {
$tlink = "http://yahoo.com";
}
break;
case 'domain3':
if(strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
$tlink = "http://example.com";
}
break;
default:
$tlink = "http://cbs.com";
break;
}
I am just wondering if there is better way to solve my situatuion:
I have 6 independent variables to check. But if any of conditions is true it shouldnt check other. Normally I would write:
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Surely you would admit it doesnt look good or it is not easy to read although it works. Do you know any other ways to write such if statement maybe using other notation or functions (switch? while?)
Yes, you can do
if (cond1 ) {
statement
} elseif ( cond2 ) {
statement
} elseif ( cond3 ) {
statement
}
See documentation
A more stylish way:
if(cond1):
statement1
elseif(cond2):
statement2
elseif(cond3):
statement3
elseif(cond4):
statement4
elseif(cond5):
statement5
elseif(cond6):
statement6
endif;
This is how you do it with a switch():
$a = 10;
$b = 100;
switch(true){
case ($a > $b):
echo 'a is bigger than b';break;
case ($b > $a):
echo 'b is bigger than a';break;
}
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Change to:
if (Cond1){
}elseif (cond2){
}elseif (cond3){
}
I have the following code which checks if some variables contain some specific words.
I'm sure there is a way to really shorter this. I'm a total noob so I can't know for sure how I can optimise this piece of code. Any help would be great..!
<?php
if (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'word') !== false)) {
echo "Doh";
} elseif (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'wurd') !== false)) {
echo "Bam";
} elseif (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'ward') !== false)) {
echo "Yes";
} elseif (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'wierd') !== false)) {
echo "No";
}
endif;
?>
if (in_array(1259, $_product->getCategoryIds())) {
$words = array(
'word' => 'Doh',
'wurd' => 'Bam',
'ward' => 'Yes',
'wierd' => 'No',
);
foreach ($words as $word => $message) {
if (false !== strpos($fabriquant, $word)) {
echo $message;
break;
}
}
}
A first optimization could be to do nested if statements:
if (in_array(1259, $_product->getCategoryIds()) {
if(strpos($fabriquant,'wurd') !== false) {
} elseif ....
}
Then you shold test for the most likely condiction as the first check, then the second most likely condition and so on ...
Because all the if blocks have a common component, it would be good to extract it and only test it once. The other unique points can be checked individually.
if ( in_array(1259, $_product->getCategoryIds()) )
{
if ( strpos($fabriquant,'word') !== false ) {
echo "Doh";
} elseif ( strpos($fabriquant,'wurd') !== false ) {
echo "Bam";
} elseif ( strpos($fabriquant,'ward') !== false ) {
echo "Yes";
} elseif ( strpos($fabriquant,'wierd') !== false ) {
echo "No";
}
}
This should be a simple question. I have a simple if/else statement:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
Is there a difference from ^^^ to this:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
I should mention that this is going into Wordpress. And until now, I've used the first part (no elseif, just a series of 'ifs'), and it works. I was just curious to know what the difference was.
Thanks!
Amit
Yes. If a condition in an if/else control is satisfied, the rest of the checks will be omitted. else if is just a nested if inside an else!
if ( is_page('english') ) { // if true, other statements are skipped
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
But in a series of ifs, all of them will be tested.
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) { // will be tested no matter what the outcome
// of the previous if statement was
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) { // the same here
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
So, if you're checking a property such as parity of a number, it's either odd or even, why do you want to bother checking other conditions if one is satisfied. It's a waste of resources. Therefore, the following code is much better
if(number_is_odd) {
}
else { // if it's not odd, it's even for sure
}
than
if(number_is_odd) {
}
if(!number_is_odd) {
}
Because the former checks the condition once whilst the latter does it twice. The same thing goes for conditions with more than two states.
The first method will check against every condition, whether they are true or false.
The second method will check against every condition until one is true, and then ignores the rest.
In your first block, every comparison in your block is executed. Also, toppic will always be assigned the value in is_page('newspaper') or the value in is_page('newspaper')'s else statement. This happens because the last if statment is always evaluated. Even if one of the previous if statements evaluated to true, you'll end up in the else block. To test this, try this code...
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'english.png';
}
if ( is_page('aboutus') ) {
$toppic = 'aboutus.png';
}
if ( is_page('newspaper') ) {
$toppic = 'newspaper.png';
}
else {
$toppic = 'finalelse.png';
}
?>
You'll always end with either 'newspaper.png' or 'finalelse.png'.
<?php
if ( 3 > 1 ) {
echo "This will be printed.";
}
if ( 3 > 2 ) {
echo "This will be printed too.";
}
if ( 3 > 3 ) {
echo "This will NOT be printed.";
}
else {
echo "This WILL be printed.";
}
?>
but with elseif:
<?php
if ( 3 > 1 ) {
echo "This will be printed.";
}
elseif ( 3 > 2 ) { /* This condition will not be evaluated */
echo "This will NOT be printed";
// because it's on the ELSE part of the previous IF
}
elseif ( 3 > 3 ) { /* This condition will not be evaluated either */
echo "This will NOT be printed.";
}
else { /* This ELSE condition is still part of the first IF clause */
echo "This will NOT be printed.";
}
?>
So you should use ELSEIF, because otherwise $toppic will always result on either 'newspaper.png', wich should be right, or 'finalelse.png' wich could be right or wrong, because it will overwrite the previous conditional clauses.
I hope you'll find this helpful.
It's not always just a question of efficiency. If you are toggling something, it is essential to use else if and not just if
Let's say we are toggling the variable $computerOn
if ($computerOn == true) {
$computerOn = false;
}
if ($computerOn == false) {
$computerOn = true;
}
In the case above your $computerOn will always be true. If it's true, it is set to false. After this, we check if it is false, which it now must be independent of initial conditions, so it is now set to true.
On the other hand the code below will toggle $computerOn:
if ($computerOn == true) {
$computerOn = false;
} elseif ($computerOn == false) {
$computerOn = true;
}
Now we only check whether $computerOn is false if it was not initially true. Hence we have a toggle.
If things get more complicated, you might have to use multiple elseifs. It's important to recognize when logic dictates that elseif is a must vs an option.
The biggest difference between the two is that the very last else block will be called whenever is_page('newspaper') returns false. In this case, it means just about every time the script runs. In this case, it's not a big deal, since you're only setting a variable, and it's the same value as everything else. But, if it were different, you would have a very frustrating bug to track down!
Besides that, if you use separate if statements, the condition for each if is evaluated every time. Again, in this case, it's (probably) not a big deal. But, if the condition was, say...
if(delete_file('foo.png')) {
....
}
if(delete_file('bar.png')) {
....
}
if(delete_file('baz.png')) {
....
}
else {
....
}
Well, you should be able to see where this is going ;) If you use elseif, it will stop trying to evaluate once it gets a true. And, the else will only be called if nothing else is true.
The answer is simple:
if(a==1){
b
}
elsif(b==1){
c
}
equals to
if(a==1){
b
}
else{
if(b==1){
c
}
}
This is the same as
if(a==1){
b
}
if(b==1){
c
}
if it is not possible that a==1 and b==1 at the same time. Although when both if statements can be true, when b and c can be executed. This would not be possible if you use elsif there, because b==1 would only be checked if a!=1!
Use elseif wisely can save you a bunch of time since the parser doesn't need to evaluate all the conditions.