writng switch statement of an already made if-else statement in php - php

i amjust startingout in php, i wanted to know how we write the switch equivalent of the following if..else statement:
$op1 = array("12", "13", "14");
$op2 = array("15", "16", "17", "18");
//echo $op1[1];
if(count($op1)> count($op2)){
echo "wrong";
}
else{
echo "right";
}
//ouptput is "right"
i tried the switch in this, but got it all wrong. i tried this and it gave a huge error:
//switch for the if-else
switch (count($op1)>count($op2)){
case (false):
echo "it is false";
case (true):
echo "it is true";
in the output, both "it is true" and it is flase" are showing.
please give the right way to do this. Thanks

Foreach is used as in case of loop statement. I din find any loop hear.
If you have to get one by one all the values of the array you can use foreach.
foreach($array_val ad $val){
//you can use $val hear..
}

Hope this will help:
// Use switch for the if-else
switch (count($op1)>count($op2)) {
case FALSE:
echo "it is false";
break;
case TRUE:
echo "it is true";
break;
// default:
// default is not required here, as the result is either TRUE or FALSE
}

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! :)

Switch statement unusual behaviour

echo get_option('bp-username-field'); and echo get_option('bp-email-field'); respectively outputs checked and 0. but with this code both the cases are running. i.e. both hello from username and hello from email are dispayed.
switch("checked")
{
case get_option('bp-username-field'):
echo 'hello from username';
case get_option('bp-email-field'):
echo 'hello from email';
...
}
And if i change switch("0") it only echoes hello from email. Also, with swith(0) both case are running. What is this behaviour?
You have to add a break after the case. If not all cases will be executed. That is normal behavior for switch Statements
switch("checked")
{
case get_option('bp-username-field'):
echo 'hello from username';
break;
case get_option('bp-email-field'):
echo 'hello from email';
...
}
You are probably missing break
switch("checked")
{
case get_option('bp-username-field'):
echo 'hello from username';
break;
case get_option('bp-email-field'):
echo 'hello from email';
break;
...
}
When the first case gets executed, then you need to break the switch. You need to introduce break to break execution of rest of the cases that follows the selected case.
When switch(0) was called, it is the final case (as of here), so it doesn't execute the one before the second case.
switch/case does loose comparison. That's mean that "checked" == 0 is true. What you want to do is:
switch(true)
{
case get_option('bp-username-field') === "checked":
echo 'hello from username';
case get_option('bp-email-field') === "checked":
echo 'hello from email';
...
}
But in a switch statement, the condition is evaluated only once and the result is compared to each case statement. This mean that after the first case is evaluate as true, all the other case will be executed until the end of the switch. What you really want it:
if (get_option('bp-username-field') === "checked") {
echo 'hello from username';
}
if (get_option('bp-email-field') === "checked") {
echo 'hello from email';
}
Because your statement is wrong;
you should compare the variable what ever it is inside switch(variable) to all those cases. for example.
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}

Switch statement using strstr always validates as true?

I have the following switch statement.
The URL contains a referral ID e.g twitter, facebook or an email e.g mail#mail.com. This is stored as $ref
I have the following switch statement:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
case strstr($ref,'#'):
echo "email = ".$ref;
default:
echo "no referral found";
break;
}
However if URL is passed with nothing (e.g just www.mything.co.uk) then I wish to go to the default case.
Instead, I get the following output:
email = no referral found
Why does the default also include the text I set for case strstr($ref,'#') ?
OP question: "Why does the default also include the text I set for case strstr($ref,'#') ?"
Answer: there's no break; following the output, and thus falls through to the default case.
UPDATE: Addressing the issue of putting a statement within a case, I'm also including an easy work-around:
switch ($ref) {
case "twitter":
echo "twitter";
break;
case "facebook":
echo "facbeook";
break;
case "blog":
echo "blog";
break;
default:
if (strstr($ref,'#')) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
break;
}
When $ref is an empty String, then strstr($ref,'#'); returns an empty string too, this is why the case strstr($ref,'#'): matches the switch input $ref.
The problem is, you can't even use a email validation function like
filter_var($ref, FILTER_VALIDATE_EMAIL)
That would return false in case of an empty input instead of an empty string, but switch does loose comparison, meaning that an "" == false would return true:
http://php.net/manual/en/types.comparisons.php#types.comparisions-loose
Thus the only solution I see is to use an if statement using the === operator:
if($ref == 'twitter') {
echo "twitter";
} else if($ref == 'facebook') {
echo "facbeook";
} else if($ref == 'blog') {
echo "blog";
} else if($ref === filter_var($ref, FILTER_VALIDATE_EMAIL)) {
echo "email = ".$ref;
} else {
echo "no referral found";
}
That's because your test is performed like if ($ref == strstr($ref, '#')), where strstr returns false which equals an empty string. You cannot really use dynamic comparisons in switch statements. Use if..else if you need that. Alternatively, abuse switch a bit:
switch (true) {
case $ref == 'twitter':
..
case strstr($ref, '#'):
..
}
That will work:
case (strstr($ref, '#') ? true : false):
But it's not really good of practice.

Check if an array field is set in a switch statement

I have a switch statement set up which checks the value in an array field. I also want to perform slightly different logic if the array has no field with that name.
I can write the code like this, which works, but looks a little messy in my mind:
if (!isset($_GET['action']))
{
require('menu.html');
}
else
{
switch ($_GET['action'])
{
case 'debug':
require('core/actions/debug.php');
break;
case 'submit':
require('core/actions/submit.php');
break;
case 'admin':
header("Location: /login");
break;
}
}
But would it be possible for me to instead move the logic from the if statement and combine it with with my switch logic?
In JavaScript, I could do case undefined: ... as just one of the cases. Can I do something similar in PHP?
If $_GET['action'] is empty, or does have value, but its not any of the ones you want, you can do this.
switch ($_GET['action'])
{
.............
case "":
echo "empty or not setted";
break;
}
But if $_GET['action'] is not setted it will throw notices on every comparison (but it will enter in case '' anyway).
To not show the notices you could do:
switch (#$_GET['action'])
But please, don't do that!
You could do the super-switch-crazy way too:
switch(true){
case !empty($_GET['action']):
switch ($_GET['action'])
{
.............
}
break;
default:
echo "not setted or empty";
break;
}
Edit:
As #IQAndreas pointed out in the comments a interest solution could be:
switch (true)
{
case (!isset($_GET['action']):
require('menu.html');
break;
case ($_GET['action'] == 'debug'):
require('core/actions/debug.php');
break;
case ($_GET['action'] == 'submit'):
require('core/actions/submit.php');
break;
case ($_GET['action'] == 'admin'):
header("Location: /login");
break;
}
But the best way IMO to handle this situation is doing what you are already doing (checking if the var is empty or setted, before the switch..case)
if (isset($_GET['action'])){
switch ($_GET['action'])
{
.............
case "":
echo "empty";
break;
}
} else {
echo "not setted";
}

switch case isset triggered when case is -not- set

--Let me add this. This code works for me the way it is. I just do not know why it works.--
I can't figure this out.
switch ($_SERVER['QUERY_STRING']) {
case isset($_GET['test0']):
echo "test0<br>";
break;
case isset($_GET['test1']):
echo "test1<br>";
break;
case isset($_GET['test2']):
echo "test2<br>";
break;
case isset($_GET['test3']):
echo "test3<br>";
break;
case isset($_GET['test4']):
echo "test4<br>";
break;
default:
echo "no test<br>";
break;
}
When the url is index.php?test0, "test0" is shown.
When the url is index.php?test4, "test4" is shown.
When the url is index.php?test999, "no test" is shown.
When the url is index.php?tes, "no test" is shown.
When the url is index.php?, or index.php, "test0" is shown.
Why is this? The condition is not met, so should the default not be shown?
switch can't be used this way. isset() returns true or false, not something (a string, an int, etc) you can match against. What you are basically doing is:
switch ($_SERVER['QUERY_STRING']) {
case true:
echo "test0<br>";
break;
case true:
echo "test1<br>";
break;
case false:
echo "test2<br>";
break;
case false:
echo "test3<br>";
break;
case true:
echo "test4<br>";
break;
default:
echo "no test<br>";
break;
}
cases are considered from top to bottom. In this case, $_SERVER["QUERY_STRING"] is automatically type-converted to bool (which will return true in this case). The first case it sees would be test0, so it echos that. If you do that for test0-4, it will give you the false illusion that this code is working as intended, while it's not considering the edge cases.
The only way you can achieve what you want is by using multiple ifs, or by redesigning your application.
When the url is index.php?, or index.php, "test0" is shown.
Why is this? The condition is not met, so should the default not be shown?
Like a good question, your question as well contains the answer already.
You already have realized that the condition must be met even you think it is not met. Therefore you ask. So let's see which condition is met:
case isset($_GET['test0']):
echo "test0<br>";
break;
This is a test for isset($_GET['test0']) and we know with the request that this is FALSE. So this test tests for FALSE.
Now let's see against what this tests:
switch ($_SERVER['QUERY_STRING']) {
That is $_SERVER['QUERY_STRING']. So if $_SERVER['QUERY_STRING'] is FALSE the test0 will be output.
Because switch { case:} in PHP does loose comparison, the empty string $_SERVER['QUERY_STRING'] is FALSE. This is why you see the output.
Easy if you know why, right? And all so logical.
And what you wanted to test against was not $_SERVER['QUERY_STRING'] but just TRUE:
switch (TRUE)
{
case isset($_GET['test0']) :
...
}
This gets the job done, too.
<?php
$q = $_SERVER['QUERY_STRING'];
if(!empty($q) && isset($q) && strlen($q) >0 ){
$url = $q;
switch ($url){
case true;
echo $url;
break;
}
}
else {
echo "no test<br>";
}
what about
$found = false;
for($i=0;$i <=4; $i++){
if( isset($_GET['test'.$i]) ){
echo "test".$i;
$found = true;
}
}
if(!$found){
echo "no test";
}

Categories