Using just if and elseif in a php syntax - php

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.

Related

PHP elseif statements; separate elseif, or compressed into one?

I'm basically wondering if there's a difference between enumerating all the possible conditions via separate elseif statements or combining them into one (apart from readability, that is).
Example 1:
if($x == 0)
{
(condition A)
}
elseif($x == 1)
{
(condition A)
}
elseif($x == 2)
{
(condition A)
}
else
{
(condition B)
}
Example 2:
if($x == 0 || $x == 1 || $x == 2)
{
(condition A)
}
else
{
(condition B)
}
Obviously example 2 is more readable, but is it also faster (or otherwise preferred)?
The cleanest option I've seen for your code is the following:
switch($x) {
case 0:
case 1:
case 2:
(condition A)
break;
default:
(condition B)
break;
}
You could also do:
if ($x <= 2) {
// Condition A
} else {
// Condition B
}
But to answer your question:
Of the 2 statements, theoretically the second would be faster but only because PHP would be parsing 1 statement recursively rather than 3 separate statements. However, the difference is so minuscule that you probably won't be able to accurately measure it. Which means they may as well be identical. My answer above this text would be faster than either of the supplied example because there is only 1 comparison (not 3). But again, the difference is small enough that it may as well be the same.
No, they're functionally equivalent.

IF vs. SWITCH and which is more suitable for this job and why?

I'm wondering whether it is possible to replicate this kind of check in a switch statement/case:
if(isset($_POST["amount"]) && (isset($_POST["fruit"]))) {
$amount = $_POST['amount'];
$fruit = $_POST['fruit'];
if($fruit == "Please select a fruit") {
echo "<script>alert('Required Field: You must choose a fruit to receive your total')</script>";
} else if(empty($fruit) or ($amount<=0) or ($amount>50)) {
echo "<script>alert('Required Field: You must enter an amount between 0-50g to receive your total')</script>";
} ... and further on
Note: I'm paying more attention to the && comparison that can be done simply in one IF, and whether this is possible to be done in a switch case and receive results like the nested if/else would. If it's not possible, why? and which method would be more efficient and why?
I would rather stick with If-Else If condition rather than converting it to Switch statement.
You have to realize the the switch statement only accepts one parameter:
switch($arg)
In your case you have amount as $_POST["amount"] and fruit as $_POST["fruit"].
Your first problem is how will you pass that 2 values on the switch statement.
You cannot use a switch for this case, since you are checking a condition (isset) of two variables which produces a boolean result. Well actually you could do a switch of this condition and switch in case of true to this code and in case of false to that code. But that would not make much sense imho.
In a switch you can just check ONE variable or expression and in the cases you execute the code of whatever the result of that switch evaluation was.
So no, you cannot do a switch with these nested ifs.
edit: to make this a bit more clear, a swicth is best used when you find yourself using multiple ifs on the same variable:
if ($var < 3)
{
// do this
}
elseif ($var < 6)
{
// do that
}
else
{
// do something other
}
Would be much better written:
switch ($var)
{
case < 3:
// do this
break;
case < 6:
// do that
break;
default:
// do somehting other
}

PHP switch statement with $_GET variables

Pages such as this: PHP switch case $_GET's variables and switch case $_GET's variable's values and others have helped, but I am at a loss as to why my switch statment does not work.
A user may be directed to my page with index.php?class=className&badge=badgeName or index.php?class=className or index.php?badge=badgeName or just plain old index.php
This code works just fine
if ($_GET["badge"] && $_GET["class"]) {
echo 'Badge and Class';
} elseif ($_GET["badge"] && !$_GET["class"]) {
echo 'Badge only';
} elseif (!$_GET["badge"] && $_GET["class"]) {
echo 'Class only';
} else {
echo 'No variables';
}
But I was trying to simplify with a switch statement, whereby all works well except for the default case:
switch ($_GET) {
case $_GET["badge"] && $_GET["class"]:
echo 'Badge and Class';
break;
case $_GET["badge"] && !$_GET["class"]:
echo 'Badge Only';
break;
case !$_GET["badge"] && $_GET["class"]:
echo 'Class only';
break;
default:
echo "No badge or class";
}
Any help appreciated.
You can try something like this:
switch (true) {
case ($i ==0):
echo '$i ==0';
break;
case ($i < 1):
echo '$i < 1';
break;
case ($i > 1):
echo '$i > 1';
break;
}
For your case:
switch (true) {
case ($_GET["badge"] && $_GET["class"]):
echo 'Badge and Class';
break;
case ($_GET["badge"] && !$_GET["class"]):
echo 'Badge Only';
break;
case (!$_GET["badge"] && $_GET["class"]):
echo 'Class only';
break;
default:
echo "No badge or class";
}
As the answer are in the link you gave:
You have to enclose the switch in a foreach() loop.
$_GET is simply an array, so you will have to make a for-each loop over it, as proposed in the link
foreach ($_GET as $key => $value) {
// Switch goes here
}
Then inside this for-each you can do switch, where you use the value of $key.
How you are going to tackle this one, I haven't figured out at the moment...
[EDIT]
I would stick with the if-elseif version - if you only have those two values to check for :)
I think you misunderstand the switch() statement. It is a special case of if... else if... else if for comparing a single variable to a possible set of values. You can't include conditions (expressions that evaluate to a boolean) in the case statements. See http://www.php.net/manual/en/control-structures.switch.php for examples.
EDIT:
I must take a minute to rail against the abuse of the switch statement that is as follows:
$a=1;
$b=2;
switch(true) {
case ($a==1):
echo "first test passed";
break;
case ($b==2):
echo "second test passed";
break;
}
This compares "true" to each of the boolean results of the expressions below. Both conditions are true, the first one executes, and the break; statement skips the second one. Technically functional, wildly misleading, and I'd throttle the guy who left me this code to debug. Absolutely abominable practice. By contrast, if you switch on a value like ($a) or ($a -3) and your case statements contain comparison values like 5 and 7, or "A" and "B", a good IDE will warn you that you have duplicate case statements. You can be sure that exactly one of the case statements passes the comparison. And the people who maintain your code in future won't have to hunt you down or curse your name. Please don't use switch() this way. If you need to do it like this, use if... else if... for readability. In this way it is obvious that the tests must be checked in order and the flow of execution will be transparent.

Is it possible do use global variables in IF's?

Can somehow a variable defined in a part of an IF be accessible in another part of the same IF?
Ex:
if ($a == 1)
{
$b = "ABC";
}
elseif ($a == 2)
{
echo $b;
}
In functions i use global $variable but in IF-statements i dont know.
The reason why i'm asking this its because i'm making a registration page step-by-step.
It means that i need to check for that If-statement a lot of times and in my final step i need to gather all variables from all IFs.
There are no "global" variables the way you understand them.
All the PHP variables doomed to die with all the PHP script after it's execution.
You need some storage to keep your variables between requests.
PHP sessions is a good choice.
The IF statement in PHP does not change variable scope - unlike a function. So anything you do in an IF will be visible outside the if as long as you stay in the same scope. You don't need to use GLOBAL. Indeed, the global scope should be used as little as possible.
The global statement simply widens the scope allowing PHP to "see" things that would otherwise be hidden. You still need to understand variable scoping though since the interactions of scope are not always obvious. I suggest going back to read the excellent PHP documentation. You'll probably need to read through it a few times and experiment a bit before it clicks.
The issue with your code is that, unless it is inside a loop that you are not showing, you will never see the value of $b because the if statement is a branch and you will only ever execute one of the branches never more than 1.
Another issue with your example is that you are using linked if statements and this would be much better written as:
switch ($a) {
case 1:
$b = "ABC";
break;
case 2:
# $b will ALWAYS be empty unless you set it BEFORE the switch OR
# you loop back to the switch AFTER $a=1
echo $b;
break;
default:
echo "i is not equal to 1 or 2";
}
See: http://php.net/manual/en/control-structures.switch.php
This form is much clearer to read and much simpler & more robust as the number of cases increases.
Well no look $a only have 1 value it maybe 1 or 2 or something else if its 1 then $b = ABC and it never comes in your elseif condition and if $a is 2 then it never entered in your first condition but yes you can define $b before condition.
$b = "something";
if ($a == 1)
{
$b = "ABC"; // $b is ABC if $a = 1
}
elseif ($a == 2)
{
echo $b; // output : something, if $a = 2
}
$b = Null
if ($a == 1)
{
$b = "ABC";
}
elseif ($a == 2)
{
echo $b;
}

Basic if..elseif...else question in 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!!!!

Categories