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.
Related
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! :)
The problem is with this line:
if $var LIKE '1800%';
and I'm not sure how to fix it. Thanks.
<?php
//check to see if account number is like 1800*
if (isset($_POST['acct_number'])) {
$var = $_POST['acct_number'];
if $var LIKE '1800%'; {
//stop the code
exit;
} else {
echo 'normal account number';
}
}
?>
You need PHP not MySQL. For 1800% just check that it is found at position 0:
if(strpos($var, '1800') === 0) {
//stop the code
exit;
} else {
echo 'normal account number';
}
If it can occur anywhere like %1800% then:
if(strpos($var, '1800') !== false) {
//stop the code
exit;
} else {
echo 'normal account number';
}
Use substr function to get first 4 characters and compare it with 1800.
if(substr($var, 0, 4) == '1800')
{
// your code goes here.
}
``
Another way could be to use strpos()
if (strpos($var, '1800') === 0) {
// var starts with '1800'
}
I would use a regular expression for this preg_match('/^1800.+/', $search, $matches);
Is there any way in PHP to return at else of first statement, if the second statement which is inside of first, is false
if($first == true) {
//other code which is not necessary to mention here!
if($second == true){
// do smth
}
else{
return to the else of $first statement
}
//other code which is not necessary to mention here!
}
else{
//do smth else
}
Yes, there are multiple ways. For starters, just combine both the statements and give another condition:
if ($first == true && $second == true) {
// do smth
} elseif ($first == true && $second == false) {
// else of$first statement
} else {
//do smth else
}
This can be used as a guidance to get an idea to start. But if you can get a real world example, there can be conditions grouped, tailored to your requirement.
While there is no native way to jump to outer elses from an inner else, but you can set a flag for later processing:
$do_else = false;
if($first == true) {
//other code which is not necessary to mention here!
if($second == true){
// do smth
}
else{
$do_else = true;
}
//other code which is not necessary to mention here!
}
else{
$do_else = true;
//do smth else
}
if($do_else){
//do smth else
}
If the answers above doesn t help you in the real situation, you can create a function for execute in 'else' statements to avoid code duplication
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`
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.