Switch Statement with user input - php

as a heads up I'm new at coding.
I'm trying to make a switch statement that will give the user the number that they have inputted into its proper roman number (only numbers from 1-10).
<form action="#" method="post">
Type a number from 1-10. <input type="text" name="num"/>
<input type="submit" name="submit">
</form>
<?php
switch (isset($_POST['submit'])) {
//$num = (int)$_POST["num"];
case 1:
echo "I";
break;
case 2:
echo "II";
break;
case 3:
echo "III";
break;
case 4:
echo "IV";
break;
case 5:
echo "V";
break;
case 6:
echo "VI";
break;
case 7:
echo "VII";
break;
case 8:
echo "VIII";
break;
case 9:
echo "IX";
break;
case 10:
echo "X";
break;
}
?>
Currently, this is what I have but I don't know of a way to get the switch statement to use the number that was provided by the user. Any help?
Thanks in advance.

The input that the user will enter a number in it has a name attribute of 'num', so to get what the user has entered, you'll use $_POST['num'].
// if the form has been submitted
if(isset($_POST['submit'])) {
$num = (int) $_POST['num'];
switch($num) {
case 1:
echo "I";
break;
case 2:
echo "II";
break;
case 3:
echo "III";
break;
case 4:
echo "IV";
break;
case 5:
echo "V";
break;
case 6:
echo "VI";
break;
case 7:
echo "VII";
break;
case 8:
echo "VIII";
break;
case 9:
echo "IX";
break;
case 10:
echo "X";
break;
default:
echo 'wrong number or you probably entered a number less than 1 or higher than 10';
}
}

First you make sure you have a something
Notice I am using $_POST['num']
$num = $_POST['num'] ?? 0;
Now you check
switch($num){
case 1:
echo 'I';
break;
case 2:
echo 'II';
break;
...
...
I would do it a bit differently, and even that is not the most efficiet transformation.
echo (([1=>'I', 2=>'II',3=>'III',....,9=>'IX'])[$_POST['num']]) ?? '';

isset($_POST['submit']) returns a boolean, which is not the integer in the range 1-10 that your switch statement expects. You probably meant to use $_POST['num'].
An array is a more compact way to encapsulate your logic instead of a long and potentially error-prone switch statement. Each array index maps to a numeral as follows:
<form action="#" method="post">
Type a number from 1-10. <input type="text" name="num">
<input type="submit" name="submit">
</form>
<?php
$numerals = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
if (isset($_POST['num'])) {
echo isset($numerals[$_POST['num']]) ? $numerals[$_POST['num']] : "error";
}
?>

You can use the following solution to solve your problem:
$input = $_POST['num'];
if($input){
switch($input) {
....
}
}

Related

how to run code after a specific time

I'm trying to display some content based on a hour.
This hour is coming from DB as string field.
If the current time match or passed the time from DB, a certain content should be displayed else it's the default content
What i've tried so far :
$time = strtotime($p_objetct->getHour());
//we check if this has already passed to
//retrieve corresponding content else we display default content
if ($time >= date("h:i:sa")) {
echo 'time to display new content !';
}else{
echo 'display content default';
}
This code is not working well as you can guess 'cause if I want to display new content at 20:00:00, the 1st condition is true when the current time is 08:00:00..
I've also tried that
$time = strtotime(p_objetct->getHour());
$selection = floor((date('G',$time) / 2));
switch ($selection) {
case 0:
echo 'time between 0-2!';
break;
case 1:
echo 'time between 2-4!';
break;
case 2:
echo 'time between 4-6!';
break;
case 3:
echo 'time between 6-8!';
break;
case 4:
echo 'time between 8-10!';
break;
case 5:
echo 'time between 10-12!';
break;
case 6:
echo 'time between 12-14!';
break;
case 7:
echo 'time between 14-16!';
break;
case 8:
echo 'time between 16-18!';
break;
case 9:
echo 'time between 18-20!';
break;
case 10:
echo 'time between 20-22!';
break;
case 11:
echo 'time between 22-24!';
break;
}
But this wasnt the good approach because i cant guess in which case the time from DB will be..
Any ideas are welcomed !
Edit :
I have 2 contents (new and default).
The new content should be display from time from DB until 00:00:00 then it should be the default one
If you get only the hour in 24h format from your $p_objetct->getHour() method you can simply compare it to date('H');.
If you wat exact matches you can use:
<?php
$hourToCheck = $p_objetct->getHour();
$currentHour = date('H'); // As of PHP manual "H" returns the hour in 24h format
$contentToDisplay = "What ever you wanna display as default.";
if ($hourToCheck === $currentHour) {
$contentToDisplay = "Your matching content.";
}
If you need it as a lower bound time feel free to use and change this snippet:
<?php
$hourToCheck = $p_objetct->getHour();
$currentHour = date('H'); // As of PHP manual "H" returns the hour in 24h format
$contentToDisplay = "What ever you wanna display as default.";
if ($hourToCheck <= $currentHour) {
$contentToDisplay = "Your matching content 1.";
}
You could try to set a variable with a name based on time, matching an existing file with that name and require it with php. Like this:
<?php
$time = date('H',time());
$name_of_content_to_require = false;
switch ($time) {
case 0:
$name_of_content_to_require = '0-2';
break;
case 1:
$name_of_content_to_require = '2-4';
break;
case 2:
$name_of_content_to_require = '4-6';
break;
case 3:
$name_of_content_to_require = '6-8';
break;
case 4:
$name_of_content_to_require = '8-10';
break;
case 5:
$name_of_content_to_require = '10-12';
break;
case 6:
$name_of_content_to_require = '12-14';
break;
case 7:
$name_of_content_to_require = '14-16';
break;
case 8:
$name_of_content_to_require = '16-18';
break;
case 9:
$name_of_content_to_require = '18-20';
break;
case 10:
$name_of_content_to_require = '20-22';
break;
case 11:
$name_of_content_to_require = '22-24';
break;
}
if( $name_of_content_to_require ) {
require_once __DIR__ . $name_of_content_to_require . '.php';
} else {
die('with some error, or throw an exception');
}

Multi-lang website: Is this a smart way of doing it?

function title_of_page() {
// Get the user's location
$user_location = $_SERVER['REQUEST_URI'];
//Find just the filename
$filename = pathinfo($user_location, PATHINFO_FILENAME);
if ($user_location == "") {
switch ($filename) {
case 'intro': echo 'introduction'; break;
case 'about': echo 'about the author'; break;
case 'foreword': echo 'foreword'; break;
case 'pottery': echo 'pottery'; break;
case 'gold_jewelery': echo 'jewelry in bahrain'; break;
case 'metalwork': echo 'metalwork'; break;
case 'weaving': echo 'weaving'; break;
case 'glass': echo 'glass industry'; break;
case 'woodwork': echo 'woodwork'; break;
case 'plant': echo 'Plant-product handicrafts'; break;
case 'calligraphy': echo 'arabic calligraphy'; break;
case 'thanks': echo 'thanks & appreciation'; break;
case 'craft': echo 'craft centres'; break;
case 'videos': echo 'videos'; break;
case 'pano': echo 'panoramic'; break;
// These are the crafts subpages
case 'jasra_handicrafts': echo 'Al Jasra Handicrafts Center'; break;
case 'jasra_training': echo 'Al Jasra Training Center'; break;
case 'capital_mall': echo 'Capital Mall'; break;
case 'craft_industries': echo 'The Craft Industries Development Centre'; break;
default: echo '<img id="logo" src="img/logo.png">'; break;}
} else {
// ARABIC TITLES
switch ($user_location) {
case '/ar/intro.php': echo 'مقدمة'; break;
case '/ar/about.php': echo 'نبذة عن الكاتب'; break;
case '/ar/foreword.php.php': echo 'تقديم'; break;
case '/ar/pottery.php': echo 'الفخار'; break;
case '/ar/gold_jewelery.php': echo 'حلي الذهب والفضة واللآلئ'; break;
case '/ar/metalwork.php': echo 'الأعمال المعدنية'; break;
case '/ar/weaving.php': echo 'النسيج والتطريز وتفصيل الملابس'; break;
case '/ar/glass.php': echo 'صناعة الزجاج'; break;
case '/ar/woodwork.php': echo 'الأشغال الخشبية'; break;
case '/ar/plant.php': echo 'صناعة المنتجات من المواد المأخوذة من النباتات'; break;
case '/ar/calligraphy.php': echo 'الخط العربي'; break;
case '/ar/thanks.php': echo 'شكر وتقدير'; break;
case '/ar/craft.php': echo 'المراكز الحرفية'; break;
case '/ar/panoramic.php': echo 'بانوراما'; break;
// These are the crafts subpages
case '/ar/jasra_handicrafts.php': echo 'مركز الجسرة للحرف اليدوية'; break;
case '/ar/jasra_training.php': echo 'مركز الجسرة للتدريب'; break;
case '/ar/capital_mall.php': echo 'بمجمع العاصمة'; break;
case '/ar/craft_industries.php': echo 'مركز تنمية الصناعات الحرفية'; break;
default: echo '<img id="logo" src="../img/logo.png">'; break;}
}
}
This is currently the code i'm using. I'm building a PhoneGap app for a client of mine and the app is stationery (as in, client doesn't want a CMS). Anyway, what I want to happen is that when the user is viewing the English side of the app, it'll show the English titles however when the user is on the Arabic side of the app it'll show the same titles in Arabic.
Just wondering if i'm going the right way..?

How can I pass this variable and check if it matches?

How can I correct/simplify this and put it in an array?
A link is passing: somelink.php?w=a (or b,c,d)
I want the page (somelink.php) to determine if "w" is set, and if set and the var matches, include the specified page.
<?php
if(isset($_GET['w'])&&($GET['w'] == "a")){include("1.htm");}
if(isset($_GET['w'])&&($GET['w'] == "b")){include("2.htm");}
if(isset($_GET['w'])&&($GET['w'] == "c")){include("3.htm");}
if(isset($_GET['w'])&&($GET['w'] == "d")){include("4.htm");}
else{include("1.htm");}
?>
try using:
$w = $_GET['w'];
if(isset($w)) {
switch(strtolower($w)) {
case "a":
include("1.htm");
break;
case "b":
include("2.htm");
break;
case "c":
include("3.htm");
break;
case "d":
include("4.htm");
break;
default:
include("not-found.htm");
break;
}
}
Use a switch statement:
if(isset($_GET['w']))
{
switch($_GET['w'])
{
case 'a': include("1.html"); break;
case 'b': include("2.html"); break;
case 'c': include("3.html"); break;
case 'd': include("4.html"); break;
default: include("1.html"); break;
}
} else {
include("1.html");
}
how about a simple array
$x=array('a'=>'1.html','b'=>'2.html');
then
include $x[$GET['w']];
Like this:
if(isset($_GET['w'])){
switch($_GET['w']){
case "a":
include("1.htm");
break;
case "b":
include("2.htm");
break;
case "c":
include("3.htm");
break;
case "d":
include("4.htm");
break;
}
}
But I wouldn't do it that way. I'd make it so that the name of the page corresponds to the value being retrieved from the $_GET variable. That way you could do something like this.
if(!empty($_GET['w'])){
include($_GET['w'] . ".htm");
}
Of course, you'd want a little filtering of the $_GET var too to make sure it doesn't get something you don't want there. Maybe like this.
$acceptable_values = array("some","acceptable","values");
if(!empty($_GET['w']) && in_array($_GET['w'],$acceptable_values) ){
include($_GET['w'] . ".htm");
}
As I'm sure you are aware, passing variables directly into include statements or database queries is a TERRIBLE idea. See here for why in this case.
http://websec.wordpress.com/2010/02/22/exploiting-php-file-inclusion-overview/
You could do a few things, lets take a look at some of them.
<?php
$webpage = '';
if(isset($_GET['w']))
$webpage = strtolower($_GET['w']);
switch($webpage)
{
case 'b':
include '2.html';
break;
case 'c':
include '3.html';
break;
case 'd':
include '4.html';
break;
default:
include '1.html';
break;
}
Or we could use arrays
<?php
$webpage = '';
if(isset($_GET['w']))
$webpage = strtolower($_GET['w']);
$included_pages = array(
'a' => '1.htm',
'b' => '2.htm',
'c' => '3.htm',
'd' => '4.htm',
);
// Check inside our array
if(array_key_exists($webpage, $includes))
{
include $included_pages[$webpage];
}
else
{
// Couldn't find the site
include '1.htm';
}

Coloring with hsl and functions with my php code

I have this code done, however it is not working the way I would like. I am trying to color a piece of a string. The color is decided by a function getcolor, which is decided by a function called raw transform, which will transforma raw score into a score from 1-9 for my switch case. Can anyone offer some help? $col is assigned by another function- for arguments sake lets say it is defined as: $col= 0.
<?php
$raw= 650;
function rawtransform($raw) {
$score = (int)($raw/50)-9;
}
//==========================================================================
// Function to decide which color system //
//==========================================================================
function getcolor($score, $col)
{
switch ($score){
// to return the function best way is to declare the case outcome as a variable eg.$truecol
case 1: /*500-550(Raw Score)*/
$truecol="<span style=\"color: hsl($col,100%,90%);\">";
break;
case 2: //550-600
$truecol="<span style=\"color: hsl($col,100%,80%);\">";
break;
case 3: //600-650
$truecol="<span style=\"color: hsl($col,100%,70%);\">";
break;
case 4: //650-700
$truecol="<span style=\"color: hsl($col,100%,60%);\">";
break;
case 5: //700-750
$truecol="<span style=\"color: hsl($col,100%,50%);\">";
break;
case 6: //750-800
$truecol="<span style=\"color: hsl($col,100%,40%);\">";
break;
case 6: //800-850
$truecol="<span style=\"color: hsl($col,100%,30%);\">";
break;
case 7: //850-900;
break;
case 8: //900-950
$truecol="<span style=\"color: hsl($col,100%,20%);\">";
break;
case 9: //950-1000
$truecol="<span style=\"color: hsl($col,100%,10%);\">";
break;
}
}
$query="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
$seq=chunk_split($query,50,"<br />");
getcolor($score);
function colorSequence ($seq,$position,$truecol,$TFBSlength){
$nucleotides = str_split($seq);
foreach ($nucleotides as $index => $nucl){
if ($index == $position){
echo $truecol;
}
if ($index == $position + $TFBSlength){
echo "</span>";
}
echo $nucl;
}
echo "\n";
}
colorSequence($seq,49,$truecol,1);
?>
The output does not include the coloring of the selcted nucleotides. Anyone know why?
You do not assign the return value of getcolor($score); to a variable. I bet it should be like $truecol = getcolor($score); before calling colorSequence($seq,49,$truecol,1);.

Can I have multiple cases that do the same thing?

The first one is definitely something that works, but which one below is the efficient way?
switch($type) {
case 1:
print 'success';
break;
case 2:
print 'success';
break;
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
Since 1, 2 and 3 print do the same, can I do this?
switch($type) {
case 1, 2, 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
or
switch($type) {
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
switch($type)
{
case 1:
case 2:
case 3:
print 'success';
break;
case 4:
print 'success for type 4';
break;
}
Is the way to go!
PHP manual lists an example like your 3rd for switch:
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
I agree with the others on the usage of:
switch ($i) {
case 0: //drop
case 1: //drop
case 2: //drop
echo "i is 0, 1, or 2";
break;
// or you can line them up like this.
case 3: case 4: case 5:
echo "i is 3, 4 or 5";
break;
}
The only thing I would add is the comments for the multi-line drop through case statements, so that way you know it's not a bug when you (or someone else) looks at the code after it was initially written.

Categories