I need to find the value of a variable and use it to add a class to a div, based on a switch statement.
For example, my variable is $link and if $link has google.com IN IT at all, I need $class to equal 'google', if $link as yahoo.com IN IT at all, $class then needs to equal 'yahoo'
So, I need something like this, but I'm not sure how/or if to use preg_match or something to check and see if the $link variable has the value we are looking for in it - see 'case' text below:
switch ($link) {
case 'IF link has Google.com in it':
$class = 'google';
break;
case 'IF link has Yahoo.com in it':
$class = 'yahoo';
break;
default:
# code...
break;
}
OR if there is a better way to do this, please let me know :D
Also, I'm good with using an IF ELSE statement as well..
Thanks
You want an IF-statement, not a switch statement
I think preg_matchis not necessary here.stripos is enough for it.
$url = $link->hits;
$pos_google = stripos($url,'google.com');
$pos_yahoo = stripos($url,'yahoo.com');
if($pos_google !== false)
{
$class = 'google';
}
elseif($pos_yahoo !== false)
{
$class = 'yahoo';
}
else
{
#code
}
Seems it could be simpler:
if(ereg("google", $link)){
$class = "google";
}else if(ereg("yahoo", $link)){
$class = "yahoo";
}else{
$class = "";
}
Related
I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.
If in your $data array there is one car and one location then you can do the following to save the variables and use them later:
$loc_name = '';
$car_name = '';
foreach ($data as $key => $value) {
if ( is_special_car($value['name']) )
continue;
switch ($type) {
case 'car':
$car_name = $name;
break;
case 'location':
$loc_name = $name;
break;
default:
break;
}
if($loc_name && $car_name){
//You have a car and loc name now
}
}
If your $data array is different you will have to modify the code of course, maybe resetting the $loc_name and $car_name when you've done whatever you needed to after getting them.
I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.
I've got 3 variables:
$left_side = "'Username'";
$equation = "==";
$right_side = "'Username'";
I want to test these variables as it was an if statement like so:
if($left_side $equation $right_side) {
// do something
} else {
// do something else
}
I know this works:
if(eval("return ".$left_side." ".$equation." ".$right_side.";")) {
// do something
} else {
// do something else
}
I always tought it's 'not good' to use eval. Especially when you try to run user input.
Is there an other way to do this? I tried to google it, but it's not my friend to day ;)
You may do something like this:
function testValues($val1, $equation, $val2) {
$res = false;
switch($equation) {
case "==":
$res = $val1 == $val2;
break;
case ">":
$res = $val1 > $val2;
break;
//....
default:
throw new Exception("Unknown operator");
}
return $res;
}
and than use it like:
if(testValues($left_side,$equation,$right_side)) {
//do something
} else {
//do something
}
eval is evil. And no, there's no other (easy) solution, but maybe this one helps:
if ($equation == "==") {
if ($left_side == $right_side) {
// ... your code goes here.
} else {
// Do some other stuff.
}
}
You could use switch:
$left_side = "'Username'";
$equation = "doublequal";
$right_side = "'Username'";
switch($equation){
case 'doublequal':
if ($left_side == $right_side) {
// code
}
break;
//......
}
You should never use eval() especially with user input.
eval() is evil, but call_user_func() is evil too and every framework uses this function in one place or another.
Tools aren't evil. They are just tools. Evil is the way that we use them.
As Uncle Ben said: Great power involves great responsibility :)
I find this trick
http://gonzalo123.com/2012/03/12/how-to-use-eval-without-using-eval-in-php/
the idea is create a temporary file with the PHP source code, include this file with the standard PHP’s include functions and destroy the temporary file.
I am writing what I thought would be a simple script but I am stuck.
The scenario is that I want to create 2 strings from the GET request.
eg: domain.com/script.php?Client=A12345
In script.php it needs to grab the "Client" and create 2 variables. One is $brand and needs to grab the A or B from the URL. The Other is $id which needs to grab the 12345 from the URL.
Now, after it has these 2 variables $brand and $id it needs to have an if statement to redirect based on the brand like below
if ($brand=="A") {
header('Location: http://a.com');
}
if ($brand=="B") {
header('Location: http://b.com');
At the end of each URL I want to apend the $id though and I am unsure on how to do this.
So for example I would access the script at domain.com/script?Client=A1234 and it needs to redirect me to a.com/12345
Thanks in advance!
$fullCode = $_REQUEST['Client'];
if(strpos($fullCode, 'A') !== false) {
$exp = explode('A',$fullcode);
header('Location: http://a.com/' . $exp[1]);
}
else if(strpos($fullCode, 'B') !== false) {
$exp = explode('B',$fullcode);
header('Location: http://b.com/' . $exp[1]);
}
else {
die('No letter occurence');
}
You can easily do,
$value = $_GET['Client'];
$brand = substr($value, 0, 1);
$rest = substr($value, 1, strlen($brand)-1);
now you have the first character in $brand string and you can do the if statement and redirect the way you want...
You mean like this?
Notice: this will only work if brand is just 1 character long. If that's not the case, please give better examples.
<?php
$client = $_GET['Client'];
$brand = strtolower(substr($client, 0, 1));
$id = substr($client, 1);
if ($brand == 'a')
{
header("Location: http://a.com/$id");
}
elseif ($brand == 'b')
{
header("Location: http://b.com/$id");
}
?>
Try using:
preg_match("/([A-Z])(\d*)/",$_GET['Client'],$matches);
$matches[1] will contain the letter and $matches[2] will contain your id.
Then you can use:
if ($matches[1]=="A")
{
header('Location: http://a.com/{$matches[2]}');
}
if ($matches[1]=="B")
{
header('Location: http://b.com/{$matches[2]}');
}
suggest you could also try
$requested = $_GET["Client"];
$domain = trim(preg_replace('/[^a-zA-Z]/',' ', $requested)); // replace non-alphabets with space
$brand = trim(preg_replace('/[a-zA-Z]/',' ', $requested)); // replace non-numerics with space
$redirect_url = 'http://' . $domain . '/' . $brand;
header('Location:' . $redirect_url);
but it'd be better if you could get the domain name and brand as two individual parameters and sanitize them individually before redirecting them to prevent the overhead of extracting them from a single parameter.
Note: this expression might be useless when the domain name itself has numerics and because the Client is obtained through get a good deal of validation and sanitation would be required in reality.
$brand = strtolower($_GET['Client'][0]);
$id = substr($_GET['Client'], 1);
header("Location: http://{$brand}.com/{$id}");
If for some purpose you want to use explode, then you need to have a separator.
Let's take '_' as the separator, so your example would be something like this: domain.com/script.php?Client=A_12345
$yourstring = explode("_",$_GET["Client"]);
echo $yourstring[0];
//will output A
echo $yourstring[1];
//will output 12345
//your simple controller could be something like this
switch($yourstring[0]){
case: 'A':
header('Location: http://a.com?id='.$yourstring[1]);
exit();
break;
case: 'B':
header('Location: http://b.com?id='.$yourstring[1]);
exit();
break;
default:
//etc
}
I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.
I have a bit of a problem with my PHP code, I am assigning values to variables in different states of the flow depending on what I receive, but for some reason it keeps getting stuck at one point, here is the code.
if (isset($session)) {
//if the user is in the database
if ($row == 1) {
$from = $_GET['from'];
if (isset($from)) {
$page = $_GET['page'];
switch ($page) {
case "game":
$page = "game";
sendVars($page);//send the variable
break;
case "gallery":
$page = "gallery";
sendVars($page);//send the variable
break;
case "leaderboard":
$page = "leaderboard";
sendVars($page);//send the Variable
break;
}
}else {
$page = "game";
sendVars($page);//send the variable
}
//if the user is not in the database
}else {
//do this
}
} else {
//register
}
Now for some odd reason, it keeps setting the value of $page to game, even though I set the page variable to gallery like so http://www.mydomai.com/?from=set&page=gallery . the only reason for this that I can think of is that my switch is not working as it should? or it is bypassing the switch somehow?
Thanx in advance!
I just ran your code after removing a few of the unessersary variable assignments:
<?php
// I added this function just for testing
function sendVars($page) {
echo $page;
}
if (isset($_GET['from'])) {
$page = $_GET['page'];
switch ($page) {
case "game":
sendVars($page); //send the variable
break;
case "gallery":
sendVars($page); //send the variable
break;
case "leaderboard":
sendVars($page); //send the Variable
break;
}
} else {
$page = "game";
sendVars($page); //send the variable
}
And it all seems fine, xxx.php?from=1&page=gallery echos out "gallery", try doing a print_r($_GET) at the top of your script and see what it prints out and let us know.
On a side note I think the below may be shorter for you and still do the same thing:
if (isset($_GET['from'])) {
// Check if $_GET['page'] exsists and is either game, gallery or leaderboard
if (isset($_GET['page']) && in_array($_GET['page'], array('game', 'gallery', 'leaderboard')))
sendVars($_GET['page']);
}
else
sendVars('game');
I hope this helps
Cheers
Luke
Try doing a var_dump($page);exit; before the switch and see what it spits out.
Also you can do a var_dump($from) and see what that is spitting out - it may be that it goes to the else, so it may not even be getting to the switch.
If this is inside a function, I personally prefer guard-style clauses than constantly increasing the levels of indentation. The idea is you pick out the bad conditions (ie if something is going wrong) to "protect" the larger block of logic.
In your case that's the switch statement.
if (!isset($session))
return ...; // register
if ($row != 1)
return ...; // do this
$from = $_GET['from'];
$page = $_GET['page'];
if (isset($from)) switch ($page) {
case "game":
$page = "game";
break;
case "gallery":
$page = "gallery";
break;
case "leaderboard":
$page = "leaderboard";
break;
}
else $page = "game";
return sendVars($page);// don't need to repeat this if all cases do it!
It's just a style of code and it's not going to fix all (if any) of your problems. You actually don't need the switch block in there for this code. I can't see that it's doing anything.
You don't necessarily need the switch statement. I can't see an obvious problem with your logic but I think this will do the same thing:
if (isset($session))
{
//if the user is in the database
if ($row == 1)
{
$page = (in_array($_GET['page'],array('game','gallery','leaderboard'))) ? $_GET['page'] : "game";
sendVars($page); //send the variable
}
else //if the user is not in the database
{
//do this
}
}
else
{
//register
}
Just saw Luke used the same in_array method but 25 mins before me. Serves me right for being slow!