Basic if..elseif...else question in PHP - php

Sorry, just a very basic question on conditionals in PHP
If {}
elseif {}
else {}
If the if condition comes out to be true, will PHP still evaluate the elseif to see if that is true as well?

No. (Basic answer for a basic question)
You can read about that in depth in the PHP Manual: elseif/else if, the first example is like yours.

Not, it won't. It will just execute the if code, and then continue after the else.
In order to see it, you could check this:
if (true)
{
echo "foo inside if"
}
else if (true)
{
echo "foo inside else if"
}
else
{
echo "foo inside else";
}
echo "\nfoo after else"
The above code will print:
foo inside if
foo after else
and not
foo inside if
foo inside else if
foo after else

Nope! Once a condition is met anywhere in an if/else block, PHP exits that block and moves on. For example, in this code:
if ($a <= 3) {
echo "small";
}
elseif ($a <= 6) {
echo "medium";
}
else {
echo "large";
}
... if $a is 2, it will echo "small" because $a is <= 3, but not "medium", even though $a is also <= 6.
If you did want PHP to check subsequent conditions, you'd use multiple if statements instead. For example:
if ($b < 4) {
echo "less than 4";
}
if ($b < 8) {
echo "less than 8";
}
... would echo both "less than 4" and "less than 8" if $b were, say, 3.

As others have already mentioned, no, it will not even test the elseif condition. This is also important for situations like the following:
$a = 1;
if ($a > 0) { }
else if (++$a > 0) { } // note the increment operator
else { }
echo $a; // produces 1
Any expressions that modify values as a byproduct of the condition test will not fire either.

If the first if is true, the code will enter the if and then execute the code inside of there. Then it will exit past the else and continue on.

No, it won't. After executing the if code, it will continue execution after the else.

Not the case. As soon as the condition you specify is met in a if query, php will stop going forward with the process and will contiue on to the code that appears after the if query has been ended.

No, it won't execute else if statements as the if condition becomes true
This is general truth for if-else-if-else block in all languages
$a=1;
if($a==1){
echo "inside if";
}else if($a==2){
echo "inside else if";
}else{
echo "inside else";
}
It will have output as below:
inside if
As the value of a is 1 it won't execute else if and else block
Hope it Helps!!!!

Related

Using just if and elseif in a php syntax

This might be a noob question. I just wanna ask if it's correct to use the following codes inside a switch statement:
case 'OPTION1':
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
break;
Or do I always have to add an else at the end of every if elseif statements? Thank you!
You only need to add an else and as many else ifs as makes sense in the code, so your example is fine.
Sometimes you may want to add some default behaviour (just the same as in a switch()) which covers the - it didn't match anything else...
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
else {
$code = '';
}
But you could alternativelty say
$code = '';
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
The OP's question concerns the basics of PHP, a worthwhile subject for review whatever one's expertise may be. While a switch statement may prove useful for avoiding messy looking long if-statements, the OP's code contains a switch statement with only one case that contains itself an if control structure. So, while the syntax is correct, the switch statement appears superfluous since the if control structure could just as easily execute without being embedded in a switch statement.
As far as the usage concerning else, that provides for default code to execute in the case of one or more if-statements evaluating as false. Also, note that the else if code only evaluates when the preceding if condition returns false. To illustrate:
<?php
$a = 3;
$b = 5;
if ($a == $b) {
echo '$a and $b are equivalent';
}
else
if ($a > $b) {
echo '$a is greater than $b';
}
else
{
echo 'The rain in Spain stays mainly in the plain';
}
?>
See live code and read more here
You could optionally recode the preceding example using a switch statement as follows:
<?php
$a = 3;
$b = 5;
switch($a) {
case ($b):
echo '$a and $b are equivalent';
break;
case ($a > $b):
echo '$a is greater than $b';
break;
default:
echo 'The rain in Spain stays mainly in the plain';
break;
}
?>
See live code
With respect to the switch statement the Manual notes:
In many occasions, you may want to compare the same variable (or
expression) with many different values, and execute a different piece
of code depending on which value it equals to. This is exactly what
the switch statement is for.
#Nigel's answer is fine. I'd just add that I'll rather use elseif instead of else if for PSR-2 compliance: https://www.php-fig.org/psr/psr-2/
The behaviour between else if and elseif is just the same.

Is there any way to break if operator like as while [duplicate]

This question already has answers here:
Any way to break if statement in PHP?
(21 answers)
Closed 8 years ago.
Is there any way to break an if statement like a while loop?
while(true) {
break;
}
if(true) {
//break if
} else {
//continue execution here or miss if at all
}
Yes, using goto. Use with caution, as it's usually an indication of bad code habits elsewhere. It does have legitimate uses though (like breaking out of nested loops).
http://php.net/manual/en/control-structures.goto.php
I think your question is poorly-worded. I think this is the problem you're having:
if( foo ) {
if( bar ) {
baz();
} else {
qux();
}
} else {
qux();
}
You want to simplify this so that qux() need only be expressed once, rather than twice. A possible solution using goto exists:
if( foo ) {
if( bar ) {
baz();
} else {
goto quxLabel;
}
} else {
quxLabel:
qux();
}
This works, but I think a better solution (if possible in your case) is to compose your branch conditions. This requires that you be able to evaluate bar independently of foo, so I don't know if this applies in your case:
if( foo && bar ) baz();
else qux();
If bar depends on foo then you can still use this technique, but take advantage of the short-circuiting behaviour of the && operator:
if( foo && computeBar( foo ) ) baz();
else qux();
Simply, inverse the order and use !:
<?php
if(!true){
echo "execution here or miss if at all";
} else {
echo "Nothing";
}
View this DEMO: http://codepad.org/XdFKfY9R
The if-statement is used to branch code without repetition so there is no need for a break constructor. It's a different thing when you are using loop control statements, especially those without a given loop condition statement like:
while (1==1) {
...
}
To avoid endless loops you will need to combine branch and loop statements, perhaps that was the idea behind your question:
while (1==1) {
// do stuff
...
// special condition
if ($cancel) {
break;
}
}
if(true){
goto end;
}
else {
continue execution here or miss if at all
}
end:
/* your statement*/
try {
if (...) {
do_something();
...
throw new \Exception(); // Break here
...
}
} catch (\Exception $e) {}
// Resumes here:
do_something_now()
Using Exceptions is generally the best way to break out of loops (or anything else). They are used to indicate an error, but can be caught and handled wherever you like.

Why this statement need in php

How this statements named in php?
if($a)
$b = "Some";
I often meet in group projects this statement. And I do not like her because I do not understand how it works. So how it work? For example how php know where end this construction, coz {} is empty? When it is advantageous to use:
if($a)
$b = "Some";
Than:
if($a)
{
$b = "Some";
}
Sorry if the question is stupid. But I want to understand why this statement need without {}
Thanks
For single line statements you dont have to provide braces({}).
But for better readability and avoid any error, in case you might need to add multiple statements later, it is recommended to use block statments.
When you omit the braces it will only treat the next statement as body of the condition.
if ($x) echo 'foo';
is the same as
if ($x) { echo 'foo'; }
but remember that
if ($x)
echo 'foo';
echo 'bar';
will always print "bar"
Internally it's the other way around: if will only look at the next expression, but PHP treats everything in {} as a single "grouped" expression.
Same for the other control statements (foreach, and so on)
As mentioned before - its shorthand for a single if statement. Just some more infos:
if($a)
$b = "Some";
is the same as
if($a) {
$b = "Some";
}
But remember that
if($a)
$b = "Some";
$c = "More";
Is similar to
if($a) {
$b = "Some";
}
$c = "More";
The if statement executes the following statement if its condition is true. The following statement can either be a single statement, or it can be a group of statements grouped together with {}. You can use {} even without if, it just won't do much on its own.
// pretty useless, but valid
{
echo 'Foo';
echo 'Bar';
}
// valid, one statement following
if (true) echo 'Baz';
// valid, group of statements following
if (true) {
echo 'Foo';
echo 'Bar';
}
try it and test this code
$b = "testing";
if($b == "testing")
echo "This is if";
echo "This is another if";
echo "This is another";
echo "This is so on";
here I use only if so I don't need to define scope OR write braces in if condition I can use multiple messages, in below code I use else there is also no need to define scope OR braces. But in if there're multiple line of code some you'll confuse about your own code and also other programmers are.
$a = "test";
if($a == "test")
echo "This is if";
else
echo "This is else";
But for example if I create a if statement and it contains one line message in if body like upper code it'll work without any error BUT if I add one more line of code OR message in if body it'll return error
$a = "test";
if($a == "test")
echo "This is if";
echo "This is if 2";
else
echo "This is else";
so I've to use braces for if condition like this
$a = "test";
if($a == "test") {
echo "This is if";
echo "This is if 2";
} else
echo "This is else";
now it'll not return error because I use braces in if condition. Remember one line of code in if body will not return any error but second line of code in if condition will return error. Braces will define the scope of your if body as you can see in the third code I didn't use braces in else because it have one line of code OR message.
You will run into a nightmare of problems if there are multiple if statements. The above (without using braces) does work only for the first set of if statement.
Second thing would be if you add braces {....} , That would add the readability to your code and your code does look organized.
By definition the if statement reads only one statement after it. If you have many statements you should group them as one using {}

Check if numeric and compare value in conditional with &&?

In PHP, if there is a conditional like this:
if ( is_numeric($my_var) && $my_var == 1 ) {
}
If the first part of the if is false, does the second part ($my_var == 1) get ever executed?
Thanks!
In your example the $my_var == 1 will not be executed (if it's not numeric). PHP will determinate that the first part evaluated to false and so there is no benefit in executing the second part because you are using the && AND operator.
An example:
if(isset($_GET['something']) && $_GET['something'] == '1')
{
}
If the querystring variable something is missing then it doesn't check if it equals 1. If it did then it could produce an Undefined index notice.
You can also verify this behavior with something like:
$test = '2';
if($test == '1' && die('dead'))
{
}
echo 'execution continues....';
Set $test = '2' and the die() will not stop execution. Set it to 1 and the die will execute and stop, thus you won't see Execution continues...
Edit: there is some general information here (not PHP specific).
If the first condition is false second one will not be executed if you use &&. You can try it yourself:
function a(){
echo 'a';
return true;
}
function b(){
echo 'b';
return true;
}
if (a() && b())
{
//do something
}
This will output: ab.
function a(){
echo 'a';
return false;
}
function b(){
echo 'b';
return true;
}
if (a() && b())
{
//do something
}
Outputs a.
I gave you this example because I couldn't find anything in docs but the first comment in this section
This is called a call-by-need or lazy evaluation.
Note: In some cases it's useful or necessary that the second function is executed despite of the state of first condition. In that cases you can use & operator. With bitwise operators you work with numbers, not with booleans. Because php interpretator should know both value before and after & operator it will execute both functions (a() & b()) and true, false are evaluated as 1 and 0, respectively, 1 & 0 => 0 that will be evaluated as false in if statement.
You can use like
if ( is_numeric($my_var)) {
if($my_var == 1)
{
// your code
}
}

Programmimg Logic

Am new to the world of coding and have difficulty is understanding the logic below. Appreciate it if someone could explain it to me. Let me start off with If statements.
/* Sample Code */
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
My understanding is that IF the first statement fails, progress to the second statement i.e. if $username does not equal to 123 then test whether it is abc. Is that correct?
Now, let me expand on that same code with else statements
/* Sample Code */
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
else {
//some code here;
}
My understanding is that IF the first staement FAILS i.e. $username does not equal to 123 then test the second statement. IF the second statement fails i.e. $username does not equal to abc then proceed to ELSE which is a catchall should all preceding IF statements FAIL. Is that correct?
Let me expand on that again using ELSE IF statements
/* Sample Code */
if($username == "123") {
//some code here;
}
else if ($username == "abc") {
//some code here;
}
else {
//some code here;
}
How is this code different from 2 separate if statements? What does ELSE do in the entire block of code?
the difference between:
if() {
}
else if() {
}
and
if() {
}
if() {
}
is that the second condition in the second example is always tested, regardless of the first if condition. In the first example, the second clause only executes if the first clause is false.
In your example, since "123" is never equal to "abc", they are equivalent. In real life, the ifs don't need to be related:
if (a) {
// Do something
} else if (b) {
// Do something else
} else {
// Do something else
}
is different from
if (a) {
// Do something
}
if (b) {
// Do something else
} else {
// Do something else
}
In the second case, both a and b might be true, in which case both lines will fire. In the first case, only the first line will fire, since the else will never even be read.
In this case they are the same:
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
against
if($username == "123") {
//some code here;
}
else if ($username == "abc") {
//some code here;
}
The difference is that with else if if the first case is true the second case will never fire.
e.g.
if($username == "123") {
//some code here;
$username = "abc"
}
if ($username == "abc") {
//some code here;
}
Both code if statement code blocks will be executed where as in:
if($username == "123") {
//some code here;
$username = "abc"
}
else if ($username == "abc") {
//some code here;
}
only the first if statement code block will be executed.
You aren't right, here's how it works:
if($something == "something")
{
//code
}
if($something == "somethingelse")
{
//code
}
Both of the above will be tested regardless of what $something equals, because they are two separate if statements. So if you were to do:
$something = "something";
if($something == "something")
{
echo $something;
}
$something = "somethingelse";
if($something == "somethingelse")
{
echo $something;
}
then the output would be "somethingsomethingelse" because both are tested. Note that in an if/elseif/else structure, it would be a syntax error to put a line of code between the ending of one block and the beginning of another.
if($something == "something")
{
//code
}
else
{
//code
}
In this, the first statement will be tested, if it is true, then it will run through that code. If false, then the code in the else block will occur.
if($something == "something")
{
//code
}
elseif($something == "somethingelse")
{
//code
}
else
{
//code
}
In this it would check the first if statement, if true, then that code runs. If false, it checks the elseif statement, if true it runs that. If false it runs the else block. The else block is a catch all.
So in something like:
if(false)
{
//code
}
elseif(false)
{
//code
}
else
{
//code
}
the else block will always be run.
The same sort of thing occurs in multiconditional statements such as:
if(is_string($something) && $something == "something")
if is_string($something) is false, it won't check the second condition because they both must be true when AND is used, and if is_string($something) is true and $something == "something" is false, then the entire if condition is false, yet again because they both must be true.
if($something == "something" || $something == "somethingelse")
In this OR statement, it will check both if the first is false, because one or the other must be true in order for the if statement to be true. So if $something does equal "somethingelse" then the if statement will be considered true. However, if $something does equal "something" then the second condition won't be checked, because it already got the true condition it needs to make the statement true.
So an && condition in an if condition is like doing:
if(is_string($something))
{
if($something == "something")
{
//code
}
}
and and || statement is like doing:
if($something == "something")
{
//code
}
elseif($something == "somethingelse")
{
//same code as previous if statement
}
Here is an example:
//this would be pulled from a page called like:
//http://www.domain.com/page.php?num=5&num2=10
$num = $_GET['num']; //5
$num2 = $_GET['num2']; //10
if(!is_numeric($num))
{
echo 'Number 1 is not a number, cannot continue <br />';
}
elseif(!is_numeric($num2))
{
echo 'Number 2 is not a number, cannot continue <br />';
}
else
{
if($num > $num2)
{
echo 'Number 1 is bigger than Number 2 <br />';
}
elseif($num2 > $num)
{
echo 'Number 2 is bigger than Number 1 <br />';
}
else
{
echo 'Numbers are equal <br />';
//Since if the numbers are neither greater than or less than each other, they must be equal to one another
}//end if
//% is the modulo operator, basically returns the remainder of division
//so !($num % $num2) is if the remainder of $num / $num2 == 0, I.E. NOT(!) $num % $num2
//! basically makes it take the opposite of the result, so !(0) is true, and 0 is false
//in the same way !(true) is literally NOT true (in other words false)
//and !(false) is literally NOT false (true)
if(!($num % $num2))
{
echo 'Number 1 is a multiple of Number 2 <br />';
}
else
{
echo 'Number 1 is not a multiple of Number 2 <br />';
}//end if
if(!($num2 % $num))
{
echo 'Number 2 is a multiple of Number 1 <br />';
}
else
{
echo 'Number 2 is not a multiple of Number 1 <br />';
}//end if
echo 'The sum of the numbers is ' . $num + $num2;
}//end if
So, with this, and an input of num=5&num2=10, the output would be
Number 2 is bigger than Number 1
Number 1 is not a multiple of Number 2
Number 2 is a multiple of Number 1 //Note that both of the multiple conditions were tested, because they are separate
The sum of the numbers is 15
With this an an input of num=16&num2=3, the output would be:
Number 1 is bigger than Number 2
Number 1 is not a multiple of Number 2
Number 2 is not a multiple of Number 1
The sum of the numbers is 19
and with an input of num=16&num2=word, the only output would be
Number 2 is not a number, cannot continue
and with an input of num=4&num2=4 the output would be
Numbers are equal
Number 1 is a multiple of Number 2
Number 2 is a multiple of Number 1
The sum of the numbers is 8
My understanding is that IF the first
statement fails, progress to the
second statement i.e. if $username
does not equal to 123 then test
whether it is abc. Is that correct?
This isn't correct. Both expressions will be evaluated; however, at most one of them can be true. Your third example behaves the way you describe above.
In your second example, if $username == "123", then the block associated with the first if statement will execute; however, the "else" block associated with the second if statement will also execute.
In the first example, both "if" statements are executed. If both are true, both happen.
In your case, both can't be true, but that's no reason not to use "else". If nothing else [no pun intended], "else" will provide a semantic hint for future programmers that you're only expecting one of the two clauses to be true.
The only way for your statement:
IF the first statement fails, progress to the second statement
to be true is if the second statement was indeed in an "else" clause of the first statement.
Only in the last snippet does the code behave as you describe. When you have an if followed by a second if, both tests are performed. There is no symbiosis or relation in the code flow.
if(X1){
A;
}elseif(X2){
B;
}elseif(X3){
C;
}else{
D;
}
this means: if X1 evaulates to true then do A. If not look if X2 evaluates to true. if yes do B. if not look if X3 evaluates to true. if so do C. if not then just do D.
if(X1){
A;
}
if(X2){
B;
}
this means: if X1 evaluates to true do A. end of your first if. then another if comes: if X2 evaluates to true then do B. these two if statements are separated from eachother unlike my first example.
the alternative if syntax in php makes it a bit clearer:
My first example in alternative syntax:
if(X1):
A;
elseif(X2):
B;
elseif(X3):
C;
else:
D;
endif;
my second example:
if(X1):
A;
endif;
if(X2):
B;
endif;
here you see clearly that these two if statements are separated from eachother.

Categories