shortening this snippet of php and jquery, can it be done? - php

so I have a URL containing an array. When the page refreshes, I want to check if certain values are still present in the URL and if not, delete any cookies that may have been associated with it.
The code is as follows:
<?php if((isset($_GET['categories']) && !in_array(2, $_GET['categories']))) { ?>
if($.cookie('hf')=='1'){$.removeCookie('hf');}
<?php } if((isset($_GET['categories']) && !in_array(7, $_GET['categories']))) { ?>
if($.cookie('hb')=='1'){$.removeCookie('hb');}
<?php } if((isset($_GET['categories']) && !in_array(5, $_GET['categories']))) { ?>
if($.cookie('hp')=='1'){$.removeCookie('hp');}
<?php } if((isset($_GET['categories']) && !in_array(4, $_GET['categories']))) { ?>
if($.cookie('hw')=='1'){$.removeCookie('hw');}
<?php } ?>
This works perfectly, but is it the best way to go about checking the array and clearing any eventual cookies?
Any help or confirmation is appreciated. Thanks.

This should do it:
<?php
if(isset($_GET['categories']))
{
foreach(array(2 => 'hf', 4 => 'hw', 5 => 'hp', 7 => 'hb') as $key => $value)
{
if(!in_array($key, $_GET['categories']))
{
echo 'if($.cookie(\''.$value.'\')==\'1\'){$.removeCookie(\''.$value.'\');}';
}
}
}
?>
That's not shorter, but cleaner.

Not necessarily more readable (but could be readable if you rename function and arguments), but this is shorter and should work.
<?php function x($a,$b) {if((isset($_GET['categories']) && !in_array($a, $_GET['categories']))) { echo "if($.cookie('".$b."')=='1'){$.removeCookie('".$b."');";}
x(2,'hf');
x(7,'hb');
x(5,'hp');
x(4,'hw'); ?>

I find this solution simple and also easy to extend in the future:
$a = array("hf" => 2, "hb" => 7, "hp" => 5, "hw" => 4);
$b = filter_input(INPUT_GET, 'categories', FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY);
if ($b) {
$keys = array_keys(array_diff($a, $b));
foreach ($keys as $val) {
echo 'if($.cookie("' . $val . '")=="1"){$.removeCookie("' . $val . '");};';
}
}
Hope it helps.

Related

PHP : Is there a way, to write this if/elseif/else statement shorter?

So I have been actively learning PHP for the past days and, for practise, I wrote PHP script, which takes HTML Form values.
I tried writing script, where I have 5 persons, and you have to input your name and last name. If it matches with one of the five persons, it sends one message, if not, other. Here it is (Without form part, only PHP):
$first = $_POST["first"];
$last = $_POST["last"];
if ($first == "Jeb") {
if ($last == "Jeb") {
print "Hello!";
} else {
print "I dont know you!";
}
} elseif ($first == "Bob") {
if ($last == "Bob") {
print "Hello!";
} else {
print "I dont know you!";
}
} elseif ($first == "Bill") {
if ($last == "Bill") {
print "Hello!";
} else {
print "I dont know you!";
}
} elseif ($first == "Annie") {
if ($last == "Annie") {
print "Hello!";
} else {
print "I dont know you!";
}
} elseif ($first == "Hugo") {
if ($last == "Hugo") {
print "Hello!";
} else {
print "I dont know you!";
}
} else {
print "I dont know you!";
}
It works great, but I have question- can this be done easier / written shorter? And can this be done using switch statement?
Any respone will be apprecieted!
i can see a way using arrays
$people=array('Bob Bob', 'Bill Bill');//etc
if(in_array($first.' '.$last,$people)){
print "Hello!";
}else{
print "I dont know you!";
}
A solution using arrays. Assumes all known names are pairs of the same name (bob bob, jeb jeb, etc)
$knownNames = array("Jeb", "Bob", "Bill", "Annie", "Hugo");
if (in_array($first, $knownNames) && $first == $last)
print "Hello!";
else
print "I don't know you!"
I'd use arrays instead (avoids duplicating code/ifs)
$name = array(
'first' => $_POST["first"],
'last' => $_POST["last"]
);
$knownNames = array(
array(
'first' => 'Bob',
'last' => 'Bob'
),
array(
'first' => 'Bill',
'last' => 'Bill'
),
array(
'first' => 'Annie',
'last' => 'Annie'
),
array(
'first' => 'Hugo',
'last' => 'Hugo'
)
);
if (in_array($name, $knownNames)) {
print "Hello!";
} else {
print "I dont know you!";
}
In your example, you are making a decision based on two tests:
Do I recognize the submitted first name?
Do I recognize the submitted last name?
Then you are responding based on whether the above tests are BOTH true.
I would suggest that you separate each test into it's own function:
function isValidFirstName($name)
{
$valid_names = array('Jeb','Bob','Bill','Annie','Hugo');
return in_array($name, $valid_names);
}
function isValidLastName($name)
{
$valid_names = array('Jeb','Bob','Bill','Annie','Hugo');
return in_array($name, $valid_names);
}
$first = $_POST['first'];
$last = $_POST['last'];
if( isValidFirstName($first) && isValidLastName($last) )
{
print "Hello!";
} else
{
print "I don't know you!";
}

Multiple IDs in PHP call in WordPress

** I apologize for being unclear - I meant I want "Summit Sponsors" to display once regardless of how many IDs are used. Just for it to be hidden if no IDs are used. Thanks **
I was wondering if anyone knew a clean way to use multiple custom fields in an IF statement.
At the moment I have it spaced out, so each custom field "SponsorHeading#" has it's own if/else statement:
<?php
if(get_post_meta($post_id, 'SponsorHeading1', true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
if(get_post_meta($post_id, 'SponsorHeading2', true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
?>
and so on for 3 more custom fields. I'd like to have something cleaner like:
<?php
if(get_post_meta($post_id, 'SponsorHeading1', true)) || if(get_post_meta($post_id, 'SponsorHeading2', true)) || if(get_post_meta($post_id, 'SponsorHeading3', true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
?>
or something along those lines to clean it up but nothing I've tried has worked.
Any suggestions?
Not 100% sure on if there is a more efficient way to manage this within WordPress’s logic itself, but the simplest solution I can conceive of using the example you give is to put all of the ids into an array & have logic to loop through them like so:
<?php
$fields = array('SponsorHeading1', 'SponsorHeading2', 'SponsorHeading3');
foreach($fields as $field_value) {
if(get_post_meta($post_id, $field_value, true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
}
?>
EDIT: Addressing the user edits to the question. So how about this? We loop through the fields, and the value of $has_value changes to TRUE if at least one of the fields is returned by get_post_meta(). And if $has_value is TRUE then act on it:
<?php
$fields = array('SponsorHeading1', 'SponsorHeading2', 'SponsorHeading3');
$has_value = FALSE;
foreach($fields as $field_value) {
if(get_post_meta($post_id, $field_value, true)) {
$has_value = TRUE;
}
}
if ($has_value) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
?>

Shorthand to check value in array

Is there a short way of doing this?
if ((isset($a['key']) && ($a['key'] == 'value')) {
echo 'equal';
// more code
}
else {
echo 'not equal';
// more code
}
I need to test lots of values on an array that can or cannot exist. I feel that this method is too verbose.
I could remove the isset() and mute the notices... but then I feel dirty.
Edit:
Answering Jack's question: "Could you give an example how you would test lots of values in an array?"
example:
if (isset($_GET['action']) && $_GET['action'] == 'view') {
//code
}
if (isset($_GET['filter']) && $_GET['filter'] == 'name') {
//code
}
if (isset($_GET['sort']) && $_GET['sort'] == 'up') {
//code
}
if (isset($_GET['tag']) && $_GET['tag'] == 'sometag') {
//code
}
etc...
For anyone still stumbling upon this question...
You could use PHP's coalescing operator:
if (($a['key'] ?? '') === 'value') {
echo 'equal';
// more code
}
else {
echo 'not equal';
// more code
}
See this question: using PHP's null coalescing operator on an array
I don't like to answer my own questions but I feel that the best and cleaner way to do this kind of checkings is to write a "helper funcion" like:
function iskeyval(&$a, $k, $v) {
return isset($a['key']) && ($a['key'] == 'value');
}
and then:
if (iskeyval($a, 'key', 'value')) {
...
}
else {
...
}
I have added comments to explain the code. Here is the code :
//this array maps the function with the get parameters
$functions = array (
"action" => "do_actions" ,
"filter" => "do_filters"
);
foreach ($_GET as $key=>$value) {
//check if this field is corresponding functions or not
if ( array_key_exists($key , $functions) ) {
call_user_func($functions[$key] , $key,$value);
}
}
function do_actions ($key , $value) {
//place your code here to play with this value
echo 'do_actions is called with ' . $key . 'and' . $value . "</br>";
}
function do_filters ($key , $value) {
//place your code here to play with this value
echo 'do_filters is called with ' . $key . ' and ' . $value . "</br>";
}
?>
$list = array(
0 => 'one',
1 => 'two',
2 => 'one',
3 => 'three',
4 => 'one',
);
if( #$list['xxx'] !== 'three')
echo 'Not ';
echo 'Equal';
Suppress the error reporting.

PHP - Run through If statements, if none are true, echo a random variable

Ok what I would like to do is somewhat unique, and I can't find anything online to guide me, so hopefully I do a good job explaining it.
PROBLEM:
I have a series of if statements in PHP. To simplify, each if statement looks like this:
if($product_name == 'shoe') {
$shoe_description = '<p>Shoe description</p>';
echo $shoe_description;
}
else if($product_name == 'car') {
$car_description = '<p>Car description</p>';
echo $car_description;
}
else if($product_name == 'bottle') {
$bottle_description = '<p>Bottle description</p>';
echo $bottle_description;
}
This works fine as long as $product_name is defined as one of my variables. What I would like to do is, as the last statement, say that "if product_name matches none of my variables, show a random description from above"; so I'll add a final else statement to the end of the above code (example - not working code):
else {
// Show one of the echo strings from above (i.e. $car_description)
//but pick randomly
}
QUESTION:
What code would I need to edit/add so that the final else statement picks one of the 3 description variables so that I can then echo it on the page?
This is a pretty basic rewrite of the logic you gave. You can usually rewrite a series of if statements into simpler logic, or into a switch statement—depending on what you're trying to accomplish. In this case, I'd check if the $product_name has a description and otherwise just pick a random key.
$product_name = $_SESSION['product_name'];
$descriptions = array(
'shoe' => '<p>Shoe description</p>',
'car' => '<p>Car description</p>',
'bottle' => '<p>Bottle description</p>',
);
if(isset($product_name) && isset($descriptions[$product_name])) {
echo $descriptions[$product_name];
} else {
echo $descriptions[array_rand($descriptions)];
}
$descriptions = array(
'shoe' => '<p>Shoe description</p>',
'car' => '<p>Car description</p>',
'bottle' => '<p>Bottle description</p>'
);
if(isset($product_name) && isset($descriptions[$product_name])){
echo $descriptions[$product_name];
} else {
echo $descriptions[array_rand($descriptions)];
}
I think the easiest would be to put your products and descriptions in a key/value pair array.
That way you can shorten your if statement, and pick one randomly (by generating a random index) in the else case without defining your descriptions twice.
-- edit --
Robert K/Alexander Larikov beat me to it :) See theirs for sample code.
I would do it like this
if(!$product_name){
$options = array('shoe','car','bottle');
$product_name = array_rand($options);
}
//your code here.
Try this:
<?php
//$product_name = ...
$list = array('shoe' => 'Shoe description', 'car' => 'Car description', 'bottle' => 'Bottle description');
echo '<p>';
if (isset($list[$product_name])) {
echo $list[$product_name];
} else {
echo $list[array_rand($list)];
}
echo '</p>';
?>
You can just put all the bottle descriptions into an array and if you hit the final else just pull a random value from the array
$descriptions = array(
'shoe' => 'Shoe description',
'car' => 'Car description',
'bottle' => 'Bottle description'
);
if($product_name = 'shoe') {
$shoe_description = '<p>'.$descriptions[$product_name].'</p>';
echo $shoe_description;
}
else if($product_name = 'car') {
$car_description = '<p>'.$descriptions[$product_name].'</p>';
echo $car_description;
}
else if($product_name = 'bottle') {
$bottle_description = '<p>'.$descriptions[$product_name].'</p>';
echo $bottle_description;
}
else {
echo '<p>'.$descriptions[array_rand($descriptions)].'</p>';
}
I think you can do the following:
$product_names = array('shoe', 'car', 'bottle');
if (!in_array($product_name, $product_names))
$product_name = $product_names[rand(0,2)];
And then add your code.
I would use a switch statement for this.
$strings = array('<p>Shoe description</p>', '<p>Car description</p>', '<p>Bottle description</p>');
switch($product_name)
{
case "shoe":
echo $strings[0];
break;
case "car":
echo $strings[1];
break;
case "bottle":
echo $strings[2];
break;
default:
echo $strings[rand(0,2)];
break;
}

Creating elegant if statements

I have the following set of if statements:
<?php
if (!empty($sn1link) && !empty($sn1)) {
echo('<button class="lbutton-content">'.$sn1.'</button>');
}
if (!empty($sn2link) && !empty($sn2)) {
echo('<button class="lbutton-content">'.$sn2.'</button>');
}
if (!empty($sn3link) && !empty($sn3)) {
echo('<button class="lbutton-content">'.$sn3.'</button>');
}
if (!empty($sn4link) && !empty($sn4)) {
echo('<button class="lbutton-content">'.$sn4.'</button>');
}
if (!empty($sn5link) && !empty($sn5)) {
echo('<button class="lbutton-content">'.$sn5.'</button>');
?>
I would like a more elegant way of combining these if statements. I've tried else if but obviously this would only display the first if statement that returns TRUE whereas I'd like to return every TRUE statement. I don't think a switch would work either.
Why not iterate and use arrays?
foreach($sn_array as $link => $text):
if(!empty($link) && !empty($text)) echo ...;
endforeach;
Perhaps a for loop with variable variables:
<?php
for ($i = 1; $i <= 5; $i++) {
$link = 'sn'.$i.'link';
$button = 'sn'.$i;
if (!empty($$link) && !empty($$button)) {
echo('<button class="lbutton-content">'.$$button.'</button>');
}
}
you should make it a loop, where the values are in an array. then only one if, and one echo statement are needed to accomplish the same thing.
$snList = array($sn1 => $sn1Link, $sn2 => $sn2Link, $sn3 => $sn3Link);
foreach ($snList as $name => $link) {
echo('<button class="lbutton-content">'.$name.'</button>');
}
you don't even need the if statement, because if the values don't exist, you simply don't add them to the $snList array in the first place.
$snList = array();
$snList[$key] = $value;
I'm not sure how much more elegant this would be but you could use a function like:
function getButtonContent($link, $content) {
if (!empty($link) && !empty($content)) {
echo('<button class="lbutton-content">'.$content.'</button>');
}
}
getButtonContent($sn1link, $sn1);
getButtonContent($sn2link, $sn2);
getButtonContent($sn3link, $sn3);
etc....
If you have this in more than on place or have something similar the function approach might help.

Categories