Is there syntax error in my code? - php

Is there a syntax error in my code? Everything seems to work ok..This is a question asked on a self study test, and I don't want to get caught in a 'stump the chump', trick question..
$i = fgets(STDIN);
switch ($i) {
case 'a':
case 'i':
case 'e':
case 'u':
case 'o':
echo("vowel\n");
default:
echo("non vowel\n");
}

While it does work, it's not quite "right". You forgot to break out of the vowel case.
Personally, however, I wouldn't use a switch for this. I would probably do:
$vowels = ['a','e','i','o','u'];
if( in_array(strtolower($i),$vowels)) {
echo "vowel\n";
}
else {
echo "consonant\n"; // the proper word for "non-vowel" :p
}
This is because you have a two-case statement: either it is, or else it isn't. switch is suboptimal for this kind of thing, and - as shown by the error in your code - more prone to errors ;)

Related

Can you use a if statement inside a switch

so I'm trying to make my own MVC website, I figured the best way to learn PHP better and tackle the big MVC issue is to start a full project. The thing is, I'm stuck at the router, I can't figure out how best to write it, I think this may be a good way at least for the moment but I'm not sure if it is a ..viable one. I was basically thinking of calling the right controller according to the switch case and then if there is a second url param(I've assumed it would be the id of a article for now) to call a method calling a single article and if there isn't a second param to call a method that calls all articles, but I would like to know if this is a bad way of doing it.
function call($controller, $id='') {
switch($controller) {
case '':
break;
case 'pages':
$controller = new PagesController();
break;
case 'articles':
require_once('controllers/' . $controller . 'Controller.php');
require_once('models/articles.php');
$controller = new ArticlesController();
if(!$id){
$controller->{ "blog" }();
}else{
$controller->{ "article" }($id);
}
break;
default:
header("HTTP/1.0 404 Not Found");
include('/views/404.php');
exit;
break;
}
}
P.S. For now I'm only working with the articles case, that's why the first case only breaks without doing anything and such. Thanks in advance.
Sure can, see the example below (this is proof of concept and not tested).
switch ($controller) {
case 'pages':
break
case 'articles':
if ($Apples != $Pears)
{
$Tomatoes="Red";
}
case "52":
case "109":
case "110":
//do nothing and exit from switch
break;
default:
if ($a == $b)
{
$c = "cats!";
}
break;
}
Note that you can also use a switch inside a switch, just like nested if statements.
If you have only 2 or 3 option then you can use if else otherwise use nested switch.
You can use if in switch also switch in another switch.

Is PHP's "alternative syntax" allowing this or is it the switch statement?

I wrote a switch statement in PHP a few days ago and it was executing multiple conditions at a time. I couldn't figure what went wrong until I noticed I accidentally wrote default; instead of break; after one of the conditions.
Once the switch statement found a matching case, it executed the code inside as well as the code inside all of the cases that followed it.
$number = 3;
switch($number){
case 1:
echo 'One';
default; // who needs break
case 2:
echo 'Two';
default;
case 3:
echo 'Three';
default;
case 4:
echo 'Four';
default;
case 5:
echo 'Five';
default;
default:
echo 'Other';
}
This returns ThreeFourFiveOther (http://codepad.org/37zvAPiW).
Keep in mind, PHP never returned an error for this. Does the logic of switch statements permit my code above or is it PHP's "alternative syntax"?
It works because PHP allows semicolon ; to be used the same way : in switch syntax, i.e.
switch($a) {
case 1; // semicolon
// foo
break;
}
is the same as
switch($a) {
case 1:
// foo
break;
}
therefore from the above perspective you just planted default very early and having no break caused snowball effect.
Default in each case is just normal command, and have nothing to do with default in 'else' branch.
When the case isn't terminated/break with break command, another cases are executed too. In this case it's the same as if you remove default commands from cases, because these defaults do nothing.
switch($number){
case 1:
echo 'One';
case 2:
echo 'Two';
case 3:
echo 'Three';
case 4:
echo 'Four';
case 5:
echo 'Five';
default:
echo 'Other';
}
It works if you do use break statements: http://codepad.org/mFjlaVxz

Issue with switch statement and $_GET

I have an issue with this switch case, I will be glad if someone could give me a hint on what's going wrong.
The lines below keep on adding the case 1, 2 or 3 below the default one (centre_1) instead of replacing it.
I can't find where it goes wrong. Here is the code :
<?php include("mx/centre_1.php");
if(!isset($_GET['page'])) {
$page='centre_mx.php';
} else {
switch($_GET['page']) {
case'centre_1':
include('/mx/centre_1.php');
break;
case'centre_2':
include('/mx/centre_2.php');
break;
case'centre_3':
include('/mx/centre_3.php');
break;
}
}
?>
Any assistance will be helpful.
The reason '/mx/centre_1.php' is always being displayed is because you have it at the top of your code, outside of the if and switch statement. Due to this it'll be included on every page load.
In order to only have '/mx/centre_1.php' appear when no other option is selected you need to make it the default switch case.
$page = '';
if(in_array('page', $_GET)) {
$page = $_GET['page'];
}
switch($page) {
case 'centre_2':
include('/mx/centre_2.php');
break;
case 'centre_3':
include('/mx/centre_3.php');
break;
default:
include('/mx/centre_1.php');
}
The default case in a switch statement will happen when none of the other cases match the variable provided. That is, if $_GET['page'] doesn't equal centre_2 or centre_3 then the default code will be performed.
I'd suggest reading up more on switch statements here, since you don't seem to understand how they work.

php switch statement limit

PHP script that I'm using contains the switch statement and break to prevent the code from running into the next case automatically:
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
// some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
}
How can I prevent users to write in URL as "$a" some number that does not exist in php switch statement?
For example, in this example above, if someone writes as a url indes.php?a=5 should get a message that the link is not correct. What is the best way to do that?
Another thing that interests me, is there any limit on the number of switch statements that it is wise to use on one page or can the size of that page can cause the problem if it is to too large?
Add this to the end of the switch.
default:
echo 'not correct';
break;
From php docs:
A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
http://php.net/manual/en/control-structures.switch.php
Add the default case.
default:
echo 'Invalid Option';
break;
And there is no limit for the cases in switch.
Update:
No matter what ever the size of the page is. But surly it depends on the script or code written inside the cases. It it is time consuming than that will effect.
The placement of your default tag might be causing an issue, but I'm not 100% sure of this:
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
// some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
}
The individual case statements execute whenever there is a match with $a. For example if the user submitted 3 (thus $a==3), then case 3 would execute. It will continue to execute until the break; statement is hit. The default block is only executed if no case statements match the value contained in $a.
For example if the user submitted 5 (thus $a==5), there is no case 5: so the default block would be executed. Thusly, it's usually a standard practice to place your default: block at the end of your switch statement as follows to show that if no case statements match the condition, it will be executed last.
if (!isset($a)){
$a = '';
}
switch($a)
{
case 1:
//some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
default:
//code displayed when $a does not match any case statements
}
Hope that helps. Also, switch statements execute quite fast, they are basically similar to nested if statements. Thus there is no limit really, however, code optimization is always something you should strive for.
Your switch statement break because your using wrong structure of switch, check complete switch statement reference here
<?php
$i = 1;
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo 'no case match';
break;
}
?>

php - split switch cases in different files

I have a php file in which i am using a really very long switch case. I want to split the cases in different files (keep logically connected cases in 1 file).
EDIT: Sorry everyone it was my code that was causing problem. The switch case was working as expected.
file -> a.php
echo "<br>RES = ".test(1);
function test($value) {
switch($value) {
case (1 || 2):
include("b.php");
**return $temp;**
break;
default: echo "error";
return 3;
break;
}
}
file -> b.php
switch($value) {
case 1: echo "value is 1";
**$temp = 1;**
return 1;
break;
case 2: echo "value is 2";
**$temp = 2;**
return 2;
break;
}
How do i get proper result? if the switch case of b.php is in a.php file then everything works fine.Any idea/suggestion on how to do this?
If i add $temp (bold lines) then it works...
Thanks for help in advance.
Regards
Updated response to updated question:
modify "a.php" and prefix a return infront of the "b.php" include:
return include("b.php");
http://www.php.net/manual/en/function.include.php
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it. Also, it's
possible to return values from
included files. You can take the value
of the include call as you would a
normal function. This is not, however,
possible when including remote files
unless the output of the remote file
has valid PHP start and end tags (as
with any local file). You can declare
the needed variables within those tags
and they will be introduced at
whichever point the file was included.
simple include()'s within your case/break sections?
switch($var)
{
case 1:
include('case_1.php');
break;
case 2:
include('case_2.php');
break;
default:
include('case_default.php');
break;
}
This is actually something that Scuzzy proposed (I have even left the same naming convention), but improved:
// list of files
$my_files = array(
'a' => 'case_1.php',
'b' => 'case_2.php',
'c' => 'case_3.php',
'd' => 'case_4.php',
);
// determine which one to load
if (array_key_exists($var, $my_files)) {
include($my_files[$var]);
} else {
include('case_default.php');
}
or even shorter ;) :
$f = array('a','b','c','d');
include((in_array($var,$f)?$var:'case_default').'.php');
switch($var)
{
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: //...
include('case_' . $var . '.php');
break;
default:
include('case_default.php');
break;
}

Categories