Php switch statement - how to manage repeated cases? - php

I'm building a site in which the user should be able to select from three regions where the content should be visible. I have the following regions:
Region 1: Argentina, Uruguay, Paraguay, Chile, Venezuela, Peru
Region 2: Mexico, Colombia, Ecuador, Brazil, Belize, Costa Rica, El
Salvador, Guatemala, Honduras, Nicaragua, Panama
Region 0: It should include all of the countries above
I have the following switch statement:
switch ( $countryCode ) {
case 'AR':
case 'UY':
case 'PY':
case 'CL':
case 'VE':
case 'PR':
// code to execute
break;
case 'MX':
case 'CO':
case 'EC':
case 'BR':
case 'BZ':
case 'CR':
case 'SV':
case 'GT':
case 'HN':
case 'NI':
case 'PA':
// code to execute
break;
case 'AR':
case 'UY':
case 'PY':
case 'CL':
case 'VE':
case 'PR':
case 'MX':
case 'CO':
case 'EC':
case 'BR':
case 'BZ':
case 'CR':
case 'SV':
case 'GT':
case 'HN':
case 'NI':
case 'PA':
// code to execute
break;
default:
// code to execute
break;
}
I'm having trouble with the structure of my switch code, in the part where I have to include all of the countries (Region 0). It seems that I can't repeat countries that have been declared on previous case statements (it's obvious I know), but I can't figure out the right way to do it.
Is there any way to restructure my code so there would be a case statement that includes all of the countries? If it's not posible to do it with a switch, you guys have any other suggestion?
Thank you!

As #KenWhite mentioned, group by region, then check against regions.
Your code could look something like this:
<?php
$regions = [false, false, false];
switch ( $countryCode ) {
case 'AR':
case 'UY':
case 'PY':
case 'CL':
case 'VE':
case 'PR':
$regions[0] = $regions[1] = true;
break;
case 'MX':
case 'CO':
case 'EC':
case 'BR':
case 'BZ':
case 'CR':
case 'SV':
case 'GT':
case 'HN':
case 'NI':
case 'PA':
$regions[0] = $regions[2] = true;
break;
default:
break;
}
if($regions[0]) {
//some code here
}
// etc.

If I understand the question, you have two mutually exclusive code paths and one inclusive one. I would move away from using switch and use sets (i.e. PHP arrays).
$region1 = array_combine(['AR','UY','PY','CL','VE','PR'],true);
$region2 = array_combine(['MX','CO','EC','BR','BZ','CR','SV',
'GT','HN','NI','PA',],true);
if (isset($region1[$countryCode])) {
// Region 1 specific...
}
else if (isset($region2[$countryCode])) {
// Region 2 specific...
}
if (isset($region1[$countryCode],$region2[$countryCode])) {
// Region 0 specific...
}
else {
// Default case...
}
Better yet (if possible) move the code paths to their own functions:
function region1() { }
function region2() { }
function region0() { }
$region1 = array_combine(['AR','UY','PY','CL','VE','PR'],true);
$region2 = array_combine(['MX','CO','EC','BR','BZ','CR','SV',
'GT','HN','NI','PA',],true);
if (isset($region1[$countryCode])) {
region1();
region0();
}
else if (isset($region2[$countryCode])) {
region2();
region0();
}
else {
// Default case...
}

Options A) hard code your scenario (bad idea)
function get_region($country_code){
switch ( $country_code ) {
case 'AR':
case 'UY':
case 'PY':
case 'CL':
case 'VE':
case 'PR':
return 1;
break;
case 'MX':
case 'CO':
case 'EC':
case 'BR':
case 'BZ':
case 'CR':
case 'SV':
case 'GT':
case 'HN':
case 'NI':
case 'PA':
return 2;
break;
default:
return 0;
break;
}
}
echo get_region("AR")."\n";
echo get_region("MX")."\n";
Option B) use external .ini files
regions.ini
; region 1
[1]
country[] = "AR"
country[] = "UY"
country[] = "PY"
country[] = "CL"
country[] = "VE"
country[] = "PE"
; region 2
[2]
country[] = "MX"
country[] = "CO"
country[] = "EC"
country[] = "BR"
country[] = "BZ"
country[] = "CR"
country[] = "SV"
country[] = "GT"
country[] = "HN"
country[] = "NI"
country[] = "PA"
function.php:
function get_region($country_code){
$region = parse_ini_file("regions.ini", true);
if (in_array($country_code,$region[1]['country'], false)){
return 1;
} elseif (in_array($country_code,$region[2]['country'], false)){
return 2;
} else {
return 0;
}
}
echo get_region("AR")."\n";
echo get_region("MX")."\n";

Related

PHP - Simple Cookie Not Saving (Wordpress)

I'm trying to make a language cookie, but for some reason the cookie isn't saving.
here's the code I'm using
if ( !empty($_GET['language']) ) {
setcookie('language-eclear', $_GET['language']);
}
if ( empty($_COOKIE['language-eclear']) ) {
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "fr":
include("langFiles/lang-indexFR.php");
break;
case "de":
include("langFiles/lang-indexDE.php");
break;
case "en":
include("langFiles/lang-indexEN.php");
break;
case "nl":
include("langFiles/lang-indexNL.php");
break;
default:
include("langFiles/lang-indexEN.php");
break;
}
}else{
$lang = $_COOKIE['language-eclear'];
switch ($lang){
case "fr":
include("langFiles/lang-indexFR.php");
break;
case "de":
include("langFiles/lang-indexDE.php");
break;
case "en":
include("langFiles/lang-indexEN.php");
break;
case "nl":
include("langFiles/lang-indexNL.php");
break;
default:
include("langFiles/lang-indexEN.php");
break;
}
}
?>
the if loop for setting the cookie works I tested it by echo'ing $_GET['language'];.
However it seems that the cookie isn't saving. What am I missing?
PS: I'm using a wordpress website

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

Check several field to execute switch case

I have a code to check through several fields to execute certain code as below:
switch($tag1 || $tag2 || $tag3 || $tag4 ||$tag5){
case "satay":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
break;
case "digitalmarketing":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
break;
case "chillicrab":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chilli_crab/$img_name";
break;
case "chickenrice":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chicken_rice/$img_name";
break;
case "chendol":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chendol/$img_name";
break;
}
But it does not work.
Anyone can help?
Switch support one value only. Only IF condition can have OR and AND condition.
$tags = get the tag value.
switch($tags){
case "satay":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
break;
case "digitalmarketing":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
break;
case "chillicrab":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chilli_crab/$img_name";
break;
case "chickenrice":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chicken_rice/$img_name";
break;
case "chendol":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/chendol/$img_name";
break;
}
The following should do the trick for you:
<?php
$tag1='satay';
$tag2='test2';
$tag3='digitalmarketing';
function isItThere($myTag)
{
switch($myTag)
{
case "satay":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/satay/$img_name";
echo $imgput;
break;
case "digitalmarketing":
$imgput = "/home/uploads/sandbox/jovine/Food/tags/interactive_marketing/$img_name";
echo $imgput;
break;
// etc etc
}
}
for($i=1;$i<4;$i++)
{
isItThere(${'tag'.$i});
}
?>
I have basically set up a small function that contains the switch statement and written a simple loop to test the variables.
As I said in my comment, you can't use more than one variable in the switch statement, but this will provide you a nice clean workaround to do the same thing without the need to write many long statements.

Jpgraph : database data can't insert to the bar chart using php

here is my code :
<?php
// content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_bar.php');
include("mysql _connect .php");
$code="CSC1113";
$ac_yr="2010/2011";
$sql = "SELECT results, COUNT(*) 'No_Of_grades' FROM std_results WHERE code='$code' && ac_year='$ac_yr' GROUP BY results ORDER BY results ASC";
$result = mysql_query($sql) or die(mysql_error());
while($ors = mysql_fetch_array($result)) {
$grd=$ors['results'];
switch ($grd)
{
case "A":
$datay[1]=$ors['No_Of_grades'];
break;
case "A+":
$datay[0]=$ors['No_Of_grades'];
break;
case "A-":
$datay=$ors['No_Of_grades'];
break;
case "B":
$datay[4]=$ors['No_Of_grades'];
break;
case "B+":
$datay[3]=$ors['No_Of_grades'];
break;
case "B-":
$datay[5]=$ors['No_Of_grades'];
break;
case "C":
$datay[7]=$ors['No_Of_grades'];
break;
case "C+":
$datay[6]=$ors['No_Of_grades'];
break;
case "C-":
$datay[8]=$ors['No_Of_grades'];
break;
case "D":
$datay[10]=$ors['No_Of_grades'];
break;
case "D+":
$datay[9]=$ors['No_Of_grades'];
break;
case "E":
$datay[11]=$ors['No_Of_grades'];
break;
case "AB":
$datay[12]=$ors['No_Of_grades'];
break;
case "NE":
$datay[13]=$ors['No_Of_grades'];
break;
default:
$datay[14]=$ors['No_Of_grades'];
}
}
//set vlaue zero for othe grades..
for($i=0;$i<15;$i++){
if(!isset($datay[$i])){
$datay[$i]=0;
}
}
// Create the graph. These two calls are always required
$graph = new Graph(550,320,'auto');
$graph->SetScale("textlin");
//$theme_class="DefaultTheme";
//$graph->SetTheme(new $theme_class());
// set major and minor tick positions manually
$graph->yaxis->SetTickPositions(array(0,4,8,12,16,20), array(2,6,10,14,18));
$graph->SetBox(false);
//$graph->ygrid->SetColor('gray');
$graph->ygrid->SetFill(false);
$graph->xaxis->SetTickLabels(array('A+','A','A-','B+','B','B-','C+','C','C-','D+','D','E','AB','NE','MC'));
$graph->yaxis->HideLine(false);
$graph->yaxis->HideTicks(false,false);
// Create the bar plots
$b1plot = new BarPlot($datay);
// ...and add it to the graPH
$graph->Add($b1plot);
$b1plot->SetColor("white");
$b1plot->SetFillGradient("#4B0082","white",GRAD_LEFT_REFLECTION);
$b1plot->SetWidth(25);
$graph->title->Set("Bar Gradient(Left reflection)");
// Display the graph
$graph->Stroke();
?>
here jpgrpah doesn't display..error shows : JpGraph Error: 25067 Your manually specified scale and ticks is not correct. The scale seems to be too small to hold any of the specified tick marks.
but I gave direct data for above $datay array.this code is working perfectly..like this
$datay[0]=2;
$datay[1]=5;
$datay[2]=1;
$datay[3]=2;
$datay[4]=0;
$datay[5]=0;
$datay[6]=3;
$datay[7]=0;
$datay[8]=3;
$datay[9]=0;
$datay[10]=1;
$datay[11]=1;
$datay[12]=0;
$datay[13]=1;
$datay[14]=1;
wht's the wrong with my code ....can't understand....help me...thanxx in advanced...
I think now that i understand you :
case "A-":
$datay=$ors['No_Of_grades'];
break;
should be:
case "A-":
$datay['2']=$ors['No_Of_grades'];
break;

How to get user language by ip address using php?

I need to get language of a user who have visiting my website by their IP address using PHP. how can I do it, there is any API to do this, please advise
Use the GeoIP module as has previously been suggested and then insert this code somewhere in your project:
if($country = geoip_country_code_by_name($host))
{
switch($country)
{
case "DJ":
case "ER":
case "ET":
$lang = "aa";
break;
case "AE":
case "BH":
case "DZ":
case "EG":
case "IQ":
case "JO":
case "KW":
case "LB":
case "LY":
case "MA":
case "OM":
case "QA":
case "SA":
case "SD":
case "SY":
case "TN":
case "YE":
$lang = "ar";
break;
case "AZ":
$lang = "az";
break;
case "BY":
$lang = "be";
break;
case "BG":
$lang = "bg";
break;
case "BD":
$lang = "bn";
break;
case "BA":
$lang = "bs";
break;
case "CZ":
$lang = "cs";
break;
case "DK":
$lang = "da";
break;
case "AT":
case "CH":
case "DE":
case "LU":
$lang = "de";
break;
case "MV":
$lang = "dv";
break;
case "BT":
$lang = "dz";
break;
case "GR":
$lang = "el";
break;
case "AG":
case "AI":
case "AQ":
case "AS":
case "AU":
case "BB":
case "BW":
case "CA":
case "GB":
case "IE":
case "KE":
case "NG":
case "NZ":
case "PH":
case "SG":
case "US":
case "ZA":
case "ZM":
case "ZW":
$lang = "en";
break;
case "AD":
case "AR":
case "BO":
case "CL":
case "CO":
case "CR":
case "CU":
case "DO":
case "EC":
case "ES":
case "GT":
case "HN":
case "MX":
case "NI":
case "PA":
case "PE":
case "PR":
case "PY":
case "SV":
case "UY":
case "VE":
$lang = "es";
break;
case "EE":
$lang = "et";
break;
case "IR":
$lang = "fa";
break;
case "FI":
$lang = "fi";
break;
case "FO":
$lang = "fo";
break;
case "BE":
case "FR":
case "SN":
$lang = "fr";
break;
case "IL":
$lang = "he";
break;
case "IN":
$lang = "hi";
break;
case "HR":
$lang = "hr";
break;
case "HT":
$lang = "ht";
break;
case "HU":
$lang = "hu";
break;
case "AM":
$lang = "hy";
break;
case "ID":
$lang = "id";
break;
case "IS":
$lang = "is";
break;
case "IT":
$lang = "it";
break;
case "JP":
$lang = "ja";
break;
case "GE":
$lang = "ka";
break;
case "KZ":
$lang = "kk";
break;
case "GL":
$lang = "kl";
break;
case "KH":
$lang = "km";
break;
case "KR":
$lang = "ko";
break;
case "KG":
$lang = "ky";
break;
case "UG":
$lang = "lg";
break;
case "LA":
$lang = "lo";
break;
case "LT":
$lang = "lt";
break;
case "LV":
$lang = "lv";
break;
case "MG":
$lang = "mg";
break;
case "MK":
$lang = "mk";
break;
case "MN":
$lang = "mn";
break;
case "MY":
$lang = "ms";
break;
case "MT":
$lang = "mt";
break;
case "MM":
$lang = "my";
break;
case "NP":
$lang = "ne";
break;
case "AW":
case "NL":
$lang = "nl";
break;
case "NO":
$lang = "no";
break;
case "PL":
$lang = "pl";
break;
case "AF":
$lang = "ps";
break;
case "AO":
case "BR":
case "PT":
$lang = "pt";
break;
case "RO":
$lang = "ro";
break;
case "RU":
case "UA":
$lang = "ru";
break;
case "RW":
$lang = "rw";
break;
case "AX":
$lang = "se";
break;
case "SK":
$lang = "sk";
break;
case "SI":
$lang = "sl";
break;
case "SO":
$lang = "so";
break;
case "AL":
$lang = "sq";
break;
case "ME":
case "RS":
$lang = "sr";
break;
case "SE":
$lang = "sv";
break;
case "TZ":
$lang = "sw";
break;
case "LK":
$lang = "ta";
break;
case "TJ":
$lang = "tg";
break;
case "TH":
$lang = "th";
break;
case "TM":
$lang = "tk";
break;
case "CY":
case "TR":
$lang = "tr";
break;
case "PK":
$lang = "ur";
break;
case "UZ":
$lang = "uz";
break;
case "VN":
$lang = "vi";
break;
case "CN":
case "HK":
case "TW":
$lang = "zh";
break;
default:break;
}
}
You can use any geoIP module. It allow you detect country by IP. But this is not very correct way. For example I now in Thailand (and I have thai IP), but my language is russian :)
This is not very good when google show me page in thai language.
For detect language you can use Headers from browser. Preferred languages are listed in this Headers.
While you can do a lookup on an IP address to get an idea of the general physical location, the physical location may not have much to do with the language of the person whose IP address you are looking up.
For instance while the IP location may be New York area of the United States the person may speak Mandarin as their primary language because they are visiting the area.
Here is a service that you could use for IP address lookup http://ipinfodb.com/ip_location_api.php
Here is a stackoverflow discussion Get user location by IP address in C# that might be helpful as well.
However you will need to provide a mechanism for allowing the language choice to change. And use cookies or something similar to remember the language choice.
The most common use of location information is to provide targeted advertising which is more likely to be of use to the person at that location.
EDIT: Use of mobile devices
Since mobile devices and smart phones accessing the internet over high-speed 3G and 4G cellular networks are becoming increasing common, a question is whether IP address geolocation works for those types of devices.
The short answer is, not very well. See this article, Where's that Phone?: Geolocating IP Addresses on 3G Networks from Microsoft Research.
Also, here is a stackoverflow question on mobile phone location from a HTTP request.
Here is an article, Geolocating IP addressesin Cellular Data Networks that provides some information on the problem as well.

Categories