PHP syntax for if / elseif / else but for 4 conditions - php

I need to implement 3 'if conditions' in my script, i've looked it up online but I can only find solutions up to 2 if's like below
<?
if (condition 1){
do something;
}
elseif (condition 2){
do something else;
}
else {
do this last;
}
?>
but I would need something like this:
if (condition 1) { do this };
else if (condition 2) {do that};
or else if (condition 3) {do that};
else (do this)
How do I go about this?

simply
if(condition){
}
else if(condition){
}
else if(condition){
}
else{
}
you can use switch case statements too. you can use else if as many as you want. Each condition inside if() can accept OR and AND operators as || for OR and && for AND you can use.

if (condition 1) { do this
} else if (condition 2) {do that
} else if (condition 3) {do that
} else { do this }
alternatively if you want to check one variable each time you can use a switch for example
$myvar = 5;
switch($myvar){
case 1:
//do this
break;
case 2:
//do that
break;
case 3:
//do that
break;
default:
//do this
}

You can use this construction
if ( $a == $b ) {
// something...
} else if ( $a == $c ) {
// something...
} else if ( $a == $d ) {
// something...
} else {
// otherwise...
}
But if all of the conditions are ( $a equals to something ) it's better to use switch ... case:
switch ( $a ) {
case $b:
// something...
break;
case $c:
// something...
break;
case $d:
// something...
break;
default:
// otherwise...
break;
}

Solution 1
Using many elseif statements as you want.
Use this solution when your conditions are complex, or comparing different variables.
if (/*condition 1*/) {
// Action to condition 1
} else if (/*condition 2*/) {
// Action to condition 2
} else if (/*condition 3*/) {
// Action to condition 3
} else if (/*condition n*/) {
// Action to condition n
} else {
// Action when no conditions match.
}
Solution 2
Using switch statement:
Use this condition when you want to compare a variable against constant values:
switch ($age) {
case 0:
return 'You are a baby';
break;
case 18:
return 'You are 18 years old';
break;
case 21:
case 22:
case 23:
return 'You are too old';
default:
return 'Unexpected age :(';
}

How about using the or operator, ||:
if (condition 1) { do this }
else if (condition 2 || condition 3) {do that}
else {do this}
An example:
<?php
function testCondition($a, $b) {
if ($a == $b) {
print ("They are the same<br />\n");
}
else if ($a == "a" || $b == "b") {
print ("One is the same as its letter<br />\n");
}
else {
print ("They are some other sort<br />\n");
}
}
testCondition("c","c");
testCondition("a","c");
testCondition("a","b");
testCondition("d","e");
?>
Outputs:
They are the same
One is the same as its letter
One is the same as its letter
They are some other sort

I have the same problem as first stated here. I have four variables but the second one is skipped and only 1,3, and 4 work. Why?
if(empty($fromName) or empty($fromEmail) or empty($subject) or empty($comments)) {
echo 'You cannot submit the form with empty fields. Please correct the form and resubmit.';
return false;
}
elseif($fieldDelete == "Delete this text!"){
echo "Delete the contents of the fourth field before submitting.";
return false;
}
elseif (($fromName == "Curtisvien") || ($fromName == "Thomastymn") || ($fromName == "RichardMark")) {
echo "Failed. Please try again.";
return false;
}
else {
$flgchk = mail ("$to", "$subject", "$message", "$headers");
$imgfile = "images/NatMap logo2.gif";
$handle = fopen($filename, "r");
$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));
echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" width=427 height=72 />';
echo "\n<br />\n<br />Thank You! An e-mail has been sent to the National Map web team and they will get back to you in the next 24-48 hours.";
}`enter code here`

Related

PHP: Is there an alternative to using multiple if-statements?

I am in the making of some code that needs to check if a users login details are correct, and I therefore need a lot of if-statements inside each other. If any of the conditions in the if-statements are not true, they should alle return the same value. Is there an easy way of doing this, instead of writing the same multiple times? I have made an example below to visualize my problem. As you can see here I write " else { return false; }" multiple time, and this is what I am wondering if you are able to do more efficiently. Maybe so I only have to write "or else return false" once.
//some code
if (/*some condition*/) {
//some code
if (/*some new condition*/) {
//some code
if (/*some new condition*/) {
//some code
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
I am having a hard time finding a good way to explain my problem, so if you have a more elegant way of explaining it, do not hesitate to edit my post. I am also not quite sure that the title is as good as it could be, so if you have any ideas to an alternativ please say so :)
Lets say you have something like that (I added No):
if ( condition1 ) {
//some code 1
if ( condition2 ) {
//some code 2
if ( condition3 ) {
//some code 3
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
Since each time a condition is false, you exit the function returning false, you can directly test if the condition is false using a negation (if the negated condition is true):
if ( !condition1 ) {
return false;
}
//some code 1
if ( !condition2 ) {
return false;
}
//some code 2
if ( !condition3 ) {
return false;
}
//some code 3
This doesn't reduce the number of if statements, but you avoid many nesting levels and the else statements.
You can also try the switch statement. For many situations it will produce cleaner code.
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
The switch statement is also compatible with using strings:
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
?>
Good luck! :)

How do I add an if / else?

I am using the following code to pass a variable. if variable = a, do nothing.
I then want to check if variable = a, do nothing, if b, do nothing, else do something
<?
if($_GET['pageid'] == 'a'){
} else {
include('header_image.php');
}
?>
Above is the code I have working correctly for one vartiable.
How do I add an if / else?
if($_GET['pageid'] != 'a' && $_GET['pageid'] != 'b'){
//do smth
}
This is a comment - i want the formatting...
To do what you want:
if ($_GET['pageid'] == 'a') {
// do nothing for now
}
elseif ($_GET['pageid'] == 'b') {
// do some more nothing...
}
else { // we do something...
include('header_image.php');
}
You could combine the 'do nothing' tests as:
if ( $_GET['pageid'] == 'a'
|| $_GET['pageid'] == 'b') {
// do nothing for now
}
else { // we do something...
include('header_image.php');
}
I agree it reads better than the 'not equal and' tests. However, that is what 'programmers' use so it is worthwhile getting used to it.

If statement with multiple logical comparison

I need to check if $_POST['a'] is not empty AND is either '1' OR '2' so user cannot remove the a= or change the value from 1 or 2 to something else from the post path:
<?php
if(empty($_POST['a']) || !in_array($_POST['a'], array('1', '2'))) {
echo 'error1';
} else if ($_POST['a'] == '1') {
do something;
} else if ($_POST['a'] == '2') {
do something;
} else {
echo 'error2';
}
?>
Can anyone teach me how to do this in a correct way?
Many many thanks
You can use a switch instead:
switch ($_POST['a']):
case '':
// empty
echo 'error1';
break;
case '1':
// do something for 1
break;
case '2':
// do something for 2
break;
default:
// not empty but not 1 or 2
echo 'error2';
endswitch;
if (!empty($_POST['a']) && $_POST['a'] == '1') { //Not empty AND is 1
do something;
} else if (!empty($_POST['a']) && $_POST['a'] == '2') { //Not Empty AND is 2
do something;
} else {
echo 'error';
}
The first two will catch all "good" values, everything else will get the error. And no need for the top if in this case.
UPDATE: You have a syntax error. Missing a ) at the end of the first if.
Two easy ways of doing this:
// first condition should be by itself as it's a terminal error
if(empty($_POST['a']) or !in_array($_POST['a'], array('1', '2'))) {
echo 'error1';
die; // or redirect here or just enfore a default on $_POST['a'] = 1; // let's say
}
// Second can be like this or embraced in the else of the first one (se ex.2)
if ($_POST['a'] == '1') {
// do something;
} else if ($_POST['a'] == '2') {
// do something;
}
or
// first condition should be by itself as it's a terminal error
if(empty($_POST['a']) or !in_array($_POST['a'], array('1', '2'))) {
echo 'error1';
// or redirect here or just enfore a default on $_POST['a'] = 1; // let's say
}else{ // Second is in the else here :)
if ($_POST['a'] == '1') {
// do something;
} else if ($_POST['a'] == '2') {
// do something;
}
}
Your last else will not be reached as it will always end in the first if where you handle both emptiness and illegal value.

php more readable if statement

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){
}

PHP Conditional Logic

In PHP, is the following logic allowed
If (x && y)
//Do A
Elseif (x)
// Do B
Elseif (y)
// Do C
Else
// Do D
Basically, are you allowed to use more than one elseif?
Yes:
if ($x && $y) {
//Do A
} else if ($x) {
// Do B
} else if ($y) {
// Do C
} else {
// Do D
}
Another format useful for HTML files
<?php if ($x && $y): ?>
Element A
<?php elseif ($x): ?>
Element B
<?php elseif ($y): ?>
Element C
<?php else: ?>
Element D
<?php endif;?>
Yes, although if the test is simple ($a == $b), use a switch instead:
switch ($a) {
case $b:
break;
case $c:
break;
default:
//Like else
}
Yes. Please see http://us3.php.net/elseif and http://us3.php.net/elseif.
You can use
if($x)
// for one line of code
elseif($y)
// also for one line of code
if($x) {
// for more than
// one line of code
} elseif($y) {
// also for multi-
// line codes
}
and
if($x):
// multi-line
endif;
yup
if(this == this && this == this){
//this and that
}else if(this == that || this == that){
//this or that
}else{
//anything else
}

Categories