How does PHP read if statements?
I have the following if statements in this order
if ( $number_of_figures_in_email < 6) {
-- cut: gives false
}
if($number_of_emails > 0) {
-- cut: gives false
}
if ( $number_of_emails == 0) {
-- cut: gives true
}
The code behaves randomly. It sometimes goes to the third if clause and gives me a success, while sometimes to the one of the first two if clauses when the input variables are constant.
This suggests me that I cannot code only with if statements.
It doesn't "behave randomly", it does what you tell it to do:
if ($a) {
// do A
}
if ($b) {
// do B
}
if ($c) {
// do C
}
All three ifs are independent of each other. If $a, $b and $c are all true, it'll do A, B and C. If only $a and $c are true, it'll do A and C, and so on.
If you're looking for more "interdependent" conditions, use if..else or nested ifs:
if ($a) {
// do A and nothing else
} else if ($b) {
// do B and nothing else (if $a was false)
} else if ($c) {
// do C and nothing else (if $a and $b were false)
} else {
// do D and nothing else (if $a, $b and $c were false)
}
In the above only one action will get executed.
if ($a) {
// do A and stop
} else {
// $a was false
if ($b) {
// do B
}
if ($c) {
// do C
}
}
In the above both B and C might get done, but only if $a is false.
This, BTW, is pretty universal and not at all PHP specific.
If you want to return only one of the results from many different if statements, use elseif, like this:
if ( $number_of_figures_in_email < 6) {
-- cut: gives false
}
elseif($number_of_emails > 0) {
-- cut: gives false
}
elseif ( $number_of_emails == 0) {
-- cut: gives true
}
Related
I have the following piece of code:
if (!$x = some_function(1)) {
if (!$x = some_function(2)) {
return something;
}
}
I want to know which of the following statements are equivalent:
A.
if (some_function(1)) {
$x = some_function(1));
}
else if (some_function(2)) {
$x = some_function(2));
}
else {
return something;
}
Or if it's essentially saying that it should be overridden, like so:
B.
if (some_function(1)) {
$x = some_function(1));
}
if (some_function(2)) {
$x = some_function(2));
}
if (!$x) {
return something;
}
Another way of wording the question: in an assignment within an if statement, is the variable evaluated for false first, and then assigned if false, or does the assignment happen first, and then the variable evaluated next?
The first statement is not equivalent to any of the others. It would be equivalent to this:
$x = some_function(1); // assign $x first
if(!$x){ // check if $x is falsy
$x = some_function(2); // overwrite $x (not the function itself)
if(!$x){ // check if $x is still falsy
// do stuff
}
}
Or, if the variable is not important, this is also equivalent
if(!some_function(1) && !some_function(2)){...}
the only difference is the first one always provides a value to $x, which is probably used somewhere else.
This is also the same, using ternary
$x = some_function(1) ? some_function(1) : some_function(2);
if(!$x) // do stuff
Thanks Scuzzy for the clarification -- it seems like the proper equivalent is this:
if (some_function(1)) {
$x = some_function(1));
}
if (!$x && some_function(2)) {
$x = some_function(2));
}
if (!$x) {
return something;
}
I want a statement something like:
IF(someVar == someOtherVar) {
//do some calculations here
}
It looks like this without using variables:
IF($_RESULT[priArrest]== 'No' ) {
//do some calculations here
}
I want to "build" that IF statement as $x using data from a CSV file named "matrixData"
$x='$_RESULT[';
$x.=$matrixData[0];
$x.="]='";
$x.=$matrixData[4];
$x.="'";
//$x defined as ....... $_RESULT[priArrest]== 'No'
IF($x) {
//do some calculations here
echo ('BINGO');
}
$x defined as ....... $_RESULT[priArrest]== 'No'
IF($x) always returns TRUE because $x is defined (I understand why I'm getting T all the time).
I want IF($x) to return T only if the CONTENT of $x is true.
ie: IF($x) always evaluates whether $x is TRUE, not whether $_RESULT[priArrest]=='No'
What is the syntax to return the result of $x rather than the literal $x?
I can easily ECHO what I want ($x), but would like to learn how to embed the $x into an IF()
I've tried defining $x as $$x
Tried using (just to demonstrate my ignorance):
IF ($x) {
}
IF (($x)) {
}
IF (($$x)) {
}
IF ((${$x})) {
}
IF ((&$x)) {
}
Based on results of searching various sources of PHP help.
As rmirabelle wrote in a comment, you can use the condition directly:
if ($_RESULT[$matrixData[0]] == $matrixData[4]) {
echo ('BINGO');
}
// Or use another condition:
if ($_RESULT[$matrixData[0]] < $matrixData[4]) {
echo ('BINGO');
}
You can also store this boolean value for later use:
$x = ($_RESULT[$matrixData[0]] < $matrixData[4]);
// …
if ($x) {
echo ('BINGO');
}
so say I have the php:
if(a === x)
{
echo "a";
}
if(b === y)
{
echo "b";
}
if(c === z)
{
echo "c";
}
If a = x and b = y but c doesn't = z. Is there a way to stop a and b being "echoed"?
and the same for if a = x but b doesn't = y and c = z. Is there a way to stop a and c being "echoed"?
I know that if a doesn't = x and thus you don't want b and c to be echoed then you should do:
if(a === x)
{
echo "a";
}else
{
die();
}
if(b === y)
{
echo "b";
}
if(c === z)
{
echo "c";
}
But I want to make sure that if one of the 3(a,b,c) doesn't equal the corresponding 3(x,y,z) nothing is echoed.
I also can't use:
if (a == x && b == y && c == z) {
echo "success";
}
as each hypothetical condition is huge (ie a database insert and checking whether a url is working etc...)
With an example of checking whether a url is working:
$file_headers = #get_headers("https://www.google.co.uk/");
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
}
else {
echo "Success concerning url";
}
and an example of inserting into a database:
if($result)
{
echo "Success concerning inserting information to the database";
}
Is there a method on how to do this?
Whats the context of this? Anyway, just put them inside all together:
if($a === 'x' && $b === 'y' && $c === 'z') {
// satisfied all three conditions, then proceed
} else {
// if one of them fails, stop the process
}
But I want to make sure that if one of the 3(a,b,c) doesn't equal the corresponding 3(x,y,z) nothing is echoed.
is fulfilled by this:
if (a == x && b == y && c == z) {
echo "all match";
}
Introducing boolean operators: and (&&) and or (||).
if(a === x && b === y && c === y) {
echo "a";
echo "b";
echo "c";
} else {
die();
}
Similarly, you could kill the script if any of the conditions are not true.
if(a !== x || b !== y || c !== z) {
die();
}
echo "a";
echo "b";
echo "c";
If you have many booleans (a === x) that make your conditional super long and difficult to read, you can always set the booleans to variables:
$boolA = a === x;
$boolB = b === y;
$boolC = c === y;
$boolZ = z < 0 || z >= 100 || z === (a + b + c);
if(!$boolA || !$boolB || !$boolC || !$boolZ) {
die();
}
// success
You could also make one or many functions to potentially clean up your code:
function isValid() {
// perform lots of logic
return true;
}
if(!isValid()) die();
// success
In the end of the day..the more complex your code gets, the more you should be using OOP. There are a lot of PHP frameworks that will help a beginner get started in this mindset.
Since I've been using Laravel recently, I'll use them as an example. First you have a routing file, which takes all requests to your site and dispatches them to certain classes & methods.
// Create a filter for checking if a URL is working
Route::filter('urlCheck', function()
{
$file_headers = #get_headers("https://www.google.co.uk/");
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
// return a 404 page
}
// continue with the normal response
});
// Create a route for a basic request to http://example.com/test
Route::get('test', array('before' => 'urlCheck', function() {
// create page for successful request to GET /test
}));
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){
}
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.