PHP - if statements bloated - php

The user gets several options which adds a different class into something that is read into PHP -
The below works, but it seems very inefficient and uses a lot of code. Is there a way I can cut this down?
<?php
if(get_sub_field('status') == "Upcoming"){
echo '<li class="upcoming">';
}
if(get_sub_field('status') == "Next"){
echo '<li class="next">';
}
if(get_sub_field('status') == "See what happened"){
echo '<li class="happened">';
}
?>

You could make a table that holds the available values for which you want. This way eliminates all of the if statements. Keep in mind thought that this is functionally equivalent to your code above.
$opt_vals = array(
"Upcoming",
"Next",
"See what happened"
);
$val_to_search = get_sub_field("status");
if(($key = array_search($val_to_search, $opt_vals)) !== FALSE) {
echo '<li class="' . strtolower($val_to_search) . '">';
}
Since array_search returns the key with the corresponding value, $key would hold the key, but as #Timur emphasized, a value at corresponding index 0, would evaluate to FALSE, 0, so in order to really check if it has the value we have to use the strict !== operator because 0 == NULL would evaluate to true.

you can do it with if...else if like this.
<?php
$status = get_sub_field('status');
if( $status == 'upcoming')
$class = 'upcoming';
else if( $status == 'Next' )
$class = 'next';
else if( $status == 'See what happened')
$class = 'happened';
?>
<li class="<?php echo $class; ?>"></li>

The only way you could change it is this:
echo '<li class="' . get_sub_field('status') . '">';
Otherwise there is no way around this! You have to use if and elseif or you make a switch statement
When you sill want to look if the value is valid you can make a array like a whitelist:
$valid = array(
"Upcoming",
"Next",
"See what happened"
);
And then you can check it like this:
if($value = array_search(get_sub_field("status"), $valid))
echo '<li class="' . strtolower($value) . '">';
else
echo '<li class="default">'; //if something fails

Related

Combining several targeted value's / variable in one piece

We currently use the following piece of PHP code to target (change) several variables. Though this works, is there some way to shorten it? I am guessing there is a shorter way, however we don't have any PHP knowledge.
if($form_id == 10767){
if($data['element_id'] == 13){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
if($form_id == 10767){
if($data['element_id'] == 14){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
if($form_id == 10767){
if($data['element_id'] == 16){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
if($form_id == 10767){
if($data['element_id'] == 17){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
I think it's possible to combine those element_id's into one single line, instead of targeting them seperately, right?
Something like this:
if($data['element_id'] == 13,14,16,17)
I tried a few things myself, but every time I get an error or break things.
Thank you kindly in advance.
If you load your targets into an array and then us in_array(needle, haystack) it can be easily reduced.
With a ternary operator instead of an IF it can be even more reduced.
$target_ids = array(13,14,16,17);
if($form_id == 10767){
if( in_array($data['element_id'], $target_ids)) {
$data['value'] = empty($data['value']) ? '' : '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
You're currently use the same if-statements several times, which isn't needed:
Then you should look into the documentation about "if" and about Logical Operators and you will find how to write "or":
if($form_id == 10767){
if($data['element_id'] == 13 || $data['element_id'] == 14 || ...etc... ){
if(!empty($data['value'])){
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
I also removed $data['value'] .= ''; on empty, since it doesn't do anything. (notice the ! before empty() which means that it validates if the value is not empty.)

how can i change the array value from if else statement inside a loop?

i've been hours trying to assign value in the array but every iteration the array is set to 0 and i can't understand why , here's the code ...
$AurQ = array();
$prod = '';
while ($NOTIFY = $notification->fetch_assoc()) {
print_r($AurQ);
if ($NOTIFY['notification_type_ID'] == 1) {
if (in_array($NOTIFY['qID'], $AurQ, true)) {
echo "exist";
continue;
} else {
$AurQ[] = $NOTIFY['qID']; // Adding the value to the array
$prod .= '<li><a href="http://localhost/website/link/' . $NOTIFY['qID'] . '"> <span class="AskIcon"></span><span class="noti_announce">';
$prod .= '<span class="unB">' . $NOTIFY['first_name'] . ' ' . $NOTIFY['last_name'] . '</span> ' . $NOTIFY['notify_name_en'] . ' "' . $NOTIFY['q_title'] . '"</span>';
$prod .= '<span class="noti_time"><span class="icon"></span>' . time_elapsed_string($NOTIFY['time']) . '</span></a></li>';
} // end of if doesn't exist in Array List
} //end of if
} // end of loop
The problem appears to be that you're pushing a value to the array only after checking if it already exists in that array, which it doesn't given that you're initializing it as an empty array just above it.
So, there's a logic error here, and depending on what you're trying to do, it can be fixed by moving the $AurQ[] = $NOTIFY['qID'] ; line into the else statement, or by changing your if statement from if (in_array($NOTIFY['qID'], $AurQ, true)) { to if (!in_array($NOTIFY['qID'], $AurQ, true)) {.
As you didn't mention an issue with things displaying when you didn't want them to, I'm going to assume you're looking for the former solution as opposed to the latter. So, your code will wind up looking something like this:
$AurQ = array();
$prod ='';
while($NOTIFY = $notification->fetch_assoc()) {
if ($NOTIFY['notification_type_ID'] == 1) {
if (in_array($NOTIFY['qID'], $AurQ, true)){ //If it's ALREADY in the array
echo "exist";
continue;
} else { //Otherwise we need to add it, and display it
$AurQ[] = $NOTIFY['qID'] ; // Adding the value to the array
$prod .= '<li><a href="http://localhost/website/link/'.$NOTIFY['qID'].'"> <span class="AskIcon"></span><span class="noti_announce">';
$prod .= '<span class="unB">'.$NOTIFY['first_name'].' '.$NOTIFY['last_name'].'</span> '.$NOTIFY['notify_name_en'].' "'.$NOTIFY['q_title'].'"</span>';
$prod .= '<span class="noti_time"><span class="icon"></span>'.time_elapsed_string($NOTIFY['time']).'</span></a></li>';
}// end of if doesn't exist in Array List
}//end of if
} // end of loop
Given your code you just need to move $AurQ[] = $NOTIFY['qID']; to else block.
Currently, $AurQ[] is empty and if block will never run because in_array($NOTIFY['qID'], $AurQ, true) will always return false.

I can´t transform this if statement into an if/elseif one. It won´t work. What am I doing wrong?

I´m experimenting with if/elseif, and can´t understand why it won´t work this in a Drupal 6 template.
This code works:
<?php
if ((arg(0) == 'node') && (arg(1) == 'add') || (arg(1) == 'edit')){
$node = node_load(array('nid' => arg(1)));
print '<h2>' . $title . '</h2>'; }
?>
In case I´m in node/add/whatever or node/nid/edit it shows the title variable wrapped into h2´s.
Now, I want to show something slightly different in case node/add and node/edit.
So, I´ve tried this:
<?php
if ((arg(0) == 'node') && (arg(1) == 'edit')) {
$node = node_load(array('nid' => arg(1)));
print '<h3>' . $title . '</h3>';
} elseif ((arg(0) == 'node') && (arg(1) == 'add')) {
$node = node_load(array('nid' => arg(1)));
print '<h2>' . $title . '</h2>'; }
} else {
echo ""; //it shows nothing
}
?>
And it won´t work (won´t show anything).
So, I´ve tried this:
<?php
if ((arg(0) == 'node') && (arg(1) == 'add')){
$node = node_load(array('nid' => arg(1)));
print '<h2>' . $title . '</h2>'; }
?>
<?php
if ((arg(0) == 'node') && (arg(1) == 'edit')){
$node = node_load(array('nid' => arg(1)));
print '<h3>' . $title . '</h3>';
}
?>
And in this case, it works only with node/add, but completely ignores node/edit.
What am I doing wrong?
Thanks for your advice!
The path for a node edit page is node/[nid]/edit...you need to use arg(2) instead:
if ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == 'edit')){

Wordpress QR Code Widget

Basically, I've been trying to make a simple Wordpress widget that displays a QR code with the URL of the current page. I'm using a modififed version of the simple text widget that parses PHP too.
function the_qrcode($permalink = '', $title = '') {
if($permalink && $title == '') {
$permalink = 'http://eternityofgamers.com/forums';
$title = 'Forums';
}
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data=' .$permalink. '" alt="QR: ' .$title. '"/>;
}
Can someone tell me what's wrong with this? I get a 500 error when I add it to functions.php.
You will need to use the urlencode() function. Generally as a rule of thumb all querystring values should be url encoded.
function the_qrcode( $permalink = '' ) {
if($permalink == '') {
$permalink = 'http://eternityofgamers.com/forums';
}
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data='.urlencode($permalink);
}
Now you can create your QR code with:
the_qrcode(the_permalink());
Also, you had a very bad missing equals sign. It is very important to understand the difference between = and ==. If you don't, no matter the context = and == mean two different things. = assigns the right hand side to the left. == returns true or false whether the left and right hand side are loosely equal (loosely because casting will be used if the sides are not of the same type).
Look at this example (Codepad demo):
$a = 5;
$b = 10;
if($a = 6) {
echo "This always appears because when you assign a truthy (all non-zero numbers are true) to a variable, true is returned.\n";
echo "Also a should now equal six instead of five: " . $a . "\n";
}
if($b == 10) {
echo "This will work as expected because == is a comparison not an assignment.\n";
echo "And b should still be 10: " . $b;
}
Try with:
<?php
function the_permalink( $permalink ) {
if ($permalink == '') {
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data=http://eternityofgamers.com/forums" alt="QR Code">';
} else {
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data='.$permalink;
}
}
?>
(I've corrected a bunch of syntax errors)

PHP if statement - select two different get variables?

Below is my example script:
<li><a <?php if ($_GET['page']=='photos' && $_GET['view']!=="projects"||!=="forsale") { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos\""); } ?>>Photos</a></li>
<li><a <?php if ($_GET['view']=='projects') { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos&view=projects\""); } ?>>Projects</a></li>
<li><a <?php if ($_GET['view']=='forsale') { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos&view=forsale\""); } ?>>For Sale</a></li>
I want the PHP to echo the "href="#" class="active" only when it is not on the two pages:
?page=photos&view=forsale
or
?page=photos&view=projects
I've also tried this and it doesnt work:
<li><a <?php if ($_GET['page']=='photos' && ($_GET['view']!=='projects' || $_GET['view']!=='forsale')) { echo ("href=\"#\" class=\"active\""); } else { echo ("href=\"/?page=photos\""); } ?>>Photos</a></li>
You can't do:
if ($var !== 'a' || !== 'b') ...
You have to do:
if ($var !== 'a' || $var !== 'b') ...
If you want to clean that code up I would suggest:
function active_view($content, $url, $view) {
if ($_GET['view'] == $view) {
return link($content, '#', 'active');
} else {
return link($content, $url);
}
}
function active_page_view() {
$args = func_get_args();
$content = array_shift($args);
$url = array_shift($args);
$page = array_shift($args);
if ($_GET['page'] == $page && !in_array($view, $args)) {
return link($content, '#', 'active');
} else {
return link($content, $url);
}
}
function link($content, $href, $class) {
$ret = '<a href="' . $href . '"';
if ($class) {
$ret .= ' class="' . $class . '"';
}
$ret .= '>' . $content . '</a>';
return $ret;
}
and then your code becomes:
<li><?php echo active_page_view('Photos', '/?page=photos', 'photos', 'projects', 'forsale'); ?></li>
<li><?php echo active_view('Projects', '/?page=photos&view=projects', 'projects'); ?></li>
<li><?php echo active_view('For Sale', '/?page=photos&view=forsale', 'project'); ?></li>
The above is illustrative rather than being final and complete. The point I'm trying to get across is you want to get in the habit of using some kind of templating mechanism even if you don't use a templating library (eg Smarty). You rarely want to embed complex logic into what is basically a view. If you use a library of functions (or objects) to create your markup it gives you a lot of control to escape special characters, automatically put in attributes, validate what you're putting in or whatever.
In this example, you probably want to have a data structure that represents your site navigation into which you enter what the current page is and it compares it to all the entries when dynamically constructing the navigation and automatically manipulates the links.
In addition to the problem cletus pointed out you also have an issue with the precedence of the operators. && has a higher precedence than ||. Therefore
if (
$_GET['page']=='photos'
&& $_GET['view']!=="projects"
|| $_GET['view']!=="forsale"
)
is equivalent to
if (
( $_GET['page']=='photos' && $_GET['view']!=="projects" )
|| $_GET['view']!=="forsale"
)
But you obviously want
if (
$_GET['page']=='photos'
&& ( $_GET['view']!=="projects" || $_GET['view']!=="forsale" )
)
Maybe not for two alternatives but if you have more options you might want to consider using !in_array(). e.g.
if (
'photos'=$_GET['page']
&& !in_array($_GET['view'], array("projects","forsale"))
)
<?php $view = $_GET['view'];
if($_GET['page'] == 'photos' && ($view =='projects' || $view == 'forsale'))
{
echo '<li>Photos</li>';
}
else
{
echo '<li>Photos</li>';
} ?>
if( $_GET[ 'page' ] != "photos" && $_GET[ 'view' ] != "forsale") {
...
}
else if( $_GET[ 'page' ] != "photos" && $_GET[ 'view' ] != "projects") {
...
}

Categories