Choosing more options with intval( $row) - php

I am trying to have this function working with 1 of 3 or more results (like "Yes, NO, Why not, Maybe" but i am not able to find a solution
$row['Funcionario'] = ( intval( $row['Funcionario']) == 1) ? "Yes" : "No";
The code above only gives me 2 possibilities:
Yes ($row['Funcionario'] == 1 ) or No ($row['Funcionario'] != 1)
How do I show Why not if $row['Funcionario'] == 2 or Maybe if $row['Funcionario'] == 3?

Easy way:
Define an array...
$answers = ["No", "Yes", "Why not", "Maybe"];
And get from it...
$row['Functionario'] = $answers[$row['Functionario']];
If the array is one-time use (ie. not used by other fields that may have these values), you could shorten it to:
$row['Functionario'] = ["No", "Yes", "Why not", "Maybe"][$row['Functionario']];
Readability may vary. Consider adding whitespace and/or comments to explain what's going on.

You should look into switch statements
switch ($row['Funcionario']) {
case 1:
echo 'This code will be executed if $row[\'Funcionario\'] is 1';
break;
case 2:
echo 'This code will be executed if $row[\'Funcionario\'] is 2';
break;
case "Yes":
echo 'This code will be executed if $row[\'Funcionario\'] is Yes';
break;
default:
echo 'This code will be executed if $row[\'Funcionario\'] is not any of the values before
}
You can replace the values after case with anything you want, and the following code until the next break will be executed if $row['Funcionario'] is that value.

Related

Why does the switch statement execute a case block even when a match is not found?

switch(1){
case 1: print 1; // prints 1 (as expected)
case 2: print 2; // prints 2 (even though match is not equal?)
case 3: print 3; // prints 3 (even though match is not equal?)
}
I know that most programming languages continue to execute each statement if you don't use break after each case expression match. But I'm confused as to why most languages execute a case block as a successful match on this second and third case statement.
Just to clarify:
I am aware of the behavior of the switch statement, but I don't understand the logic that it makes sense to execute a case block/statement as a successful match even though a match is not found.
UPDATE: I just updated the question to reflect most programming languages and not just PHP.
From the manual:
The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.
switch(1){
case 1:
echo 1; // echos 1 (as expected)
break; // stop!!!
case 2:
echo 2; // won't get here
break;
case 3:
echo 3; //or here
break;
}
The reason it's that way is probably because PHP borrowed the syntax from C.
However the reason it was originally this way is it helps to reduce code duplication I suspect.
If you have an if like:
if($item == 'SOUP' || $item == 'FRIES'){
eat($item);
}elseif($item == 'JUICE'){
drink($item);
}else{
use($item);
}
If switches never followed through you would need 4 cases with 'SOUP' and 'FRIES' having the same logic, without this you can make the switch nicer:
switch($item){
case 'SOUP':
case 'FRIES':
eat($item);
break;
case 'JUICE':
drink($item);
break;
default:
use($item);
break;
}
I know that PHP continues to check the switch statement cases if you don't use break after each case
Seems like you didn't understand. You missed to use the break keyword:
switch(1){
case 1: echo 1; break;
case 2: echo 2; break;
case 3: echo 3; break;
}
Note that a case statement is like an entry point in the code. After a case condition matches the code will run through all cases until the break is reached.
To your update: Note that this behaviour is the same for PHP as for most programming languages including : C, C++, Java, Javascript, ActionScript, Pascal, ....
Why does the switch statement execute a case block even when a match
is not found?
If you do not use break, it will execute all the switches, which can be helpful sometimes. for example:
switch ( count ) {
default : puts ( " ++++.....+++ " ) ;
case 4: puts ( " ++++ " ) ;
case 3: puts ( " +++ " ) ;
case 2: puts ( " ++ " ) ;
case 1: puts ( " + " ) ;
case 0:;
}
So if count is 3 you get output:
+++
++
+
If 2, you get output
++
+
if 10, you get:
++++.....+++
++++
+++
++
+
So there are times when you want your switch to execute the other cases, once it finds what you want. Like the code above.
You could do this with else if, but it would be a lot more typing.

check string function

I am currently trying to get my head around some basic php string functions. I currently use this code which determines if the username entered in long enough e.g.:
if (strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
And this works just fine. Which string function should I use though if I want to to check on a specific name? E.g. I would like to trigger a message once someone enters a specific Word in the form field.
Some expert advice would be greatly appreciated.
This link of 60 PHP validation functions is an excelent resource.
For your case as to check a name, you could use something like:
if (strtolower($_GET['name']) === 'joe') {
// Do something for Joe
}
elseif (in_array(strtolower($_GET['name']), array('dave', 'bob', 'jane')) {
// Do something else for Dave, Bob or Jane
}
The strtolower will ensure that upper, lower or mixed case names will match.
You don't need a function for that. You can use a if statement and ==:
if ( $_GET['name'] == 'Dave' )
{
// user entered 'Dave'
}
if statement, or if you plan to check against multiple names, switch().
switch($_GET['name']){
case "Eric":
//Eric
break;
case "Sally":
//Sally
break;
case "Tom":
//Tom
break;
default:
//Unknown
}
Its good practice to check that $_GET['name'] is set before using. To answer your question a good way IMO is in_array(needle,haystack)
<?php
if (!empty($_GET['name']) && strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
//From a database or preset
$names = array('Bob','Steve','Grant');
if(in_array($_GET['name'], $names)){
echo 'Name is already taken!';
exit;
}
?>
You can use strstr or stristr(case-insensitive) function, If want to search for specific word in a sentence.
Just check php mannual for strstr, and stristr.

I use switch statement to include specific file but it includes the "default" also

Here's my code
<?php
$id = isset($_GET['id']) ? $_GET['id'] : '';
switch ($id) {
default:include_once('default.php');
break;
case 'actiune':include('jocuri/actiune/index.php');
break;
case 'aventura':include('jocuri/aventura/index.php');
break;
}
?>
<!--games-->
<?php
$game = isset($_GET['game']) ? $_GET['game'] : '';
switch ($game) {
case 'nz':include('jocuri/actiune/ninja-vs-zombie/index.php');
break;
case 'aventura':include('/jocuri/aventura/index.php');
break;
}
?>
So when I try to acces case 'nz' from it also includes default from the top part. So how can i do to include only the 'nz' case?
Try moving the default statement to the bottom of the first switch statement. A switch statement goes straight down each case path, hence the need for the break keyword. The default case will always execute in the case no matter what. Putting it at the bottom will ensure it will only get executed when the cases fail.
As I understand you would like to ignore 'top part' (including file by id) when game parameter is provided.
Try to add IF statement to execute first switch-statement only if game is not provided (or not matched with your provided cases ['aventura', 'nz'])
Moreover you can do something like that:
$id = isset($_GET['id']) ? $_GET['id'] : '';
$game = isset($_GET['game']) ? $_GET['game'] : '';
$games = array('nz' => 'jocuri/actiune/ninja-vs-zombie/index.php',
'aventura' => '/jocuri/aventura/index.php');
$ids = array('actiune' => 'jocuri/actiune/ninja-vs-zombie/index.php',
'aventura' => '/jocuri/aventura/index.php');
if (array_key_exists($game, $games))
{
include($games[$game]);
}
else if (array_key_exists($id, $ids))
{
include($ids[$id]);
}
else include('default.php');
try this
<?php
$id = isset($_GET['id']) ? $_GET['id'] : '';
switch ($id) {
case 'actiune':include('jocuri/actiune/index.php');
break;
case 'aventura':include('jocuri/aventura/index.php');
break;
default:include_once('default.php');
break;
}
?>
<!--games-->
<?php
$game = isset($_GET['game']) ? $_GET['game'] : '';
switch ($game) {
case 'nz':include('jocuri/actiune/ninja-vs-zombie/index.php');
break;
case 'aventura':include('/jocuri/aventura/index.php');
break;
}
?>
(I did try to add this as a comment to osulerhia's answer but couldn't and figured it might answer the posters question if I've read it correctly).
I'm not sure if I understand your question correctly and if osulerhia's answer above is what you're looking for.
You're expecting two separate GET variables ("id" and "game") and if the game variable is "nz" you don't want to show the default from the switch statement you're using for "id"?
If that's right then you need to add some sort of logic to how you want your switch statements to play out. You then also need to consider though whether you want either of the others to show if "nz" is the value of "game". Your logic (written plainly) is currently:
Is the id variable "actiune" -> include a file
Is the id variable "aventura" -> include a file
Is the id variable anything else -> include the default file
Is the game variable "nz" -> include a file
Is the game variable "aventura" -> include a file
As you can see both of your switches are completely separate, you need to decide what you want to display and when you want to display it, for example, if you wanted everything to work as above but to not display ANYTHING from the first switch if the value of the game variable is "nz" then you could wrap it in an if statement like:
if((isset($_GET['game']) && $_GET['game'] != "nz") || (!isset($_GET['game']))) { *your original switch statement* }

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;
}
?>

how do i add two values for one case using switch?

im trying to create a website using switch commands to navigate with the contents displayed in a table via echo content. everything works fine. but one of the pages consists of multiple pages. The address looks like this website/index.php?content=home etc.
but i want to make it like this for the page consisting multiple pages website/index.php?content=home&page=1
my index code:
<?php
switch($_GET['content'])
{
case "home":
$content = file_get_contents('home.php');
$pages = file_get_contents('pages/1.php'); //like this?
break;
case "faq":
$content = file_get_contents('faq.php');
break;
default:
$content = file_get_contents('home.php');
break;
}
?>
//some code
<?php echo $content; ?>
//some code
the home php:
<?php
switch($_GET['page'])
{
default:
case "1":
$page = file_get_contents('pages/1.php');
break;
default:
$page = file_get_contents('pages/1.php');
break;
}
?>
// some code
<?php echo $page; ?>
//some code
go to page etc.
but when i do it like this the echo command shows me the code of the home.php but not the one of the page i wanna load inside of it.
i appreciate any kind of help!
"default" must logically always come last in your switch, since it will match any input that hasn't already been matched by a previous "case" statement.
If you want to do certain actions for multiple values, you can do it like this:
switch ( $var ) {
case 'foo':
case 'bar':
// Do something when $var is either 'foo' or 'bar'
break;
default:
// Do something when $var is anything other than 'foo' or 'bar'
break;
}
Try using include() instead.
Also, as #Rob said, your second switch() statement is ill formatted. default: should always be last and is used as a "catch-all" for values you didn't specify earlier.
first of all, why don't you use include() instead of file_get_contents()?
Second of all: you could use your "manager" page in this way:
<?php
$myPage = $_GET['page'];
$myContent = $_GET['content']
switch($myContent){
case "mycontent":
case "home": include('/home.php');
if(!empty($myPage)){
include ('/pages/'.$myPage.'.php');
}
break;
default:
// do whatever you want
}
?>
Be careful of (as in steweb's example) including files based on user input, even with a prepended path — remember that there's the possibility of executing untrusted code. (Imagine if $_GET['page'] is set to ../../../some-evil-file.php, for example.)
To avoid this, it's easiest to use a whitelist:
$pages = array( 1, 2, 18, 88 );
switch ( $_GET['content'] ) {
case 'home':
if ( in_array( $_GET['page'], $pages ) ) {
include 'pages/' . $_GET['page'] . '.php';
} else {
// If an invalid page is given, or no page is
// given at all, include a default page.
include 'pages/1.php';
}
break;
}

Categories