PHP: Simplify multiple || operator statements into one? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php if statement with multiple conditions
I have this code:
if(x==1 || x==2 || x==3 || x==4 )
Is there anyway to simply it shorter? For example:
if(x==1||2||3||4 )
Meaning for the statement to be true if X= 1,2,3 OR 4?
Thank you in advance.
Edit: (Thanks for all the replies, here is some clarification)
I have a while loop but only want specific database entries to be called. My code is current
<?php while(the_repeater_field('team_members','options') && get_sub_field('member_sort') == 1 : ?>
<div class="one_fourth">
<img src="<?php the_sub_field('image'); ?>" alt="" />
<p>
<?php the_sub_field('info'); ?>
<br />
<?php the_sub_field('email'); ?>
</p>
</div>
<?php endwhile; ?>
Right now it works perfectly with == 1 , but I also want to show 2,3,4 as well. I am just not sure how I should've put the code to execute 1||2||3||4
Update 2:
Okay so I used the following code, but I am guessing I am going about it the wrong way. The following code only showed the record that was equal to 1.. but not the records equal to 2,3,4... I am guess because the while loop is only running once since the statement becomes true instantly.
<?php while(the_repeater_field('team_members','options') && in_array(get_sub_field('member_sort'),array(1,2,3,4))): ?>
<div class="one_fourth">
<img src="<?php the_sub_field('image'); ?>" alt="" />
<p>
<?php the_sub_field('info'); ?>
<br />
<?php the_sub_field('email'); ?>
</p>
</div>
<?php endwhile; ?>

if (in_array($x, array(1,2,3,4))
or, even:
if (in_array($x, range(1, 4)))
OK, this question has evolved quite a bit but I think the problem is now that you want to loop over all values but only do stuff on certain conditions. You can use the continue statement to abort the current iteration and move on to the next immediately.
<?php while (the_repeater_field('team_members','options')) : ?>
<?php if (!in_array(get_sub_field('member_sort'), array(1,2,3,4))) continue; ?>
... do stuff
<?php endwhile; ?>

If you are using PHP 5.4+, you could do this:
if (in_array($x, [1,2,3,4]))
Otherwise, it's:
if (in_array($x, array(1,2,3,4)))

It depends on how many you have, and on whether there may be other conditions, but either a switch:
switch(x) {
case 1:
case 2:
case 3:
case 4:
break;
default:
// Do stuff
}
Or an array, especially for many items:
if(!in_array(x, array(1, 2, 3, 4)) {
// Do stuff
}

There is no way. Only by using arrays.

Related

PHP - Do this, and if the next part meets this criteria also do this

I'm quite new to PHP, but have no idea how to word this question.
I want to return a coloured circle if the colour has been selected elsewhere.
So if silver has been ticked, show a silver circle.
If silver and gold have been ticked, show both.
There must be an easier way to code the below, instead of having to create lots of seperate if statements and call a variable each time?
elseif's wouldn't work here from my understanding.
Forgive me for my naivety!
The code I've written below:
<?php
// for iphone
$colours_available = get_field('iphone_colours_available');
// check
if( $colours_available && in_array('silver', $colours_available) ): ?>
<div class="colour-circle-title"><p>Silver</p></div>
<?php endif; ?>
<?php
// vars
$colours_available = get_field('iphone_colours_available');
// check
if( $colours_available && in_array('gold', $colours_available) ): ?>
<div class="colour-circle-title"><p>Gold</p></div>
<?php endif; ?>
Thanks so much for any help!
As mentioned in comments, you can iterate through your $colours_available array, and then use ucwords() to camel-case your p-tag's text:
<?php $colours_available = get_field('iphone_colours_available'); ?>
<?php foreach($colours_available as $color) :; ?>
<div class="colour-circle-title"><p><?php echo ucwords($color); ?></p></div>
<?php endforeach; ?>
Note: If you don't need to use the $colours_availble array elsewhere, you could eliminate that line and replace it wtih get_field('iphone_colours_available') in the loop. Also, this solution does not address sorting, which your previous solution does. For that, I would recommend looking at PHP's sorting functions, specifically uasort, uksort, and usort

Hide html when included inside php if condition

I would like to present some php with the help of html formatting.
My purpose is to print:
Life status: dead (1850 in New-York)
or (if not dead):
Life status: alive
The place and date should only by printed if the condition $life_status is set to "dead".
The following code works for the dead situation but not for the alive one.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status="dead"):?>
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
</li>
<?php endif; ?>
</ul>
For the alive sitation, I obtain:
Life status: Alive ( in ).
How can I applied the php condition on "( in)."?
Your operator for checking if $life_status is dead is wrong. It is a single equal and should be double. Code below reflects these changes and implements what #AmericanUmlaut correctly suggested in the comment above to make your html actually valid.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status == "dead"):?> // This maybe the issue, wrong operator used to evaluate.
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
<?php endif; ?>
</li>
</ul>
You are using the wrong operator. = is assignment, == tests equality.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status=="dead"):?> // == here instead of =
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
<?php endif; ?>
</li>
</ul>
(Note that I also moved the outside of the if block to address the issue I noted in my comment.)
In Php strings are not compared directly and may not give the results which are intended. Therefore, using strcmp(); function will do the work. It returns 0 when 2 strings compared are equal and is a case sensitive function.
In your case:
<h3>Title</h3>
<ul>
<li>
Life status: <?php
echo ( !strcmp($life_status,"dead") ) ? 'Dead ( '.$date_death.' in '.$place_death.' ).' : 'Alive' ;
?>
</li>
</ul>
I have used the Php Ternary operator known as Shorthand if/else.
The ! will reverse the 0 to 1 if its true to show the Dead output and else will show the Alive output.
Php Ternary : http://php.net/manual/en/language.operators.comparison.php
Php strcmp() : http://php.net/manual/en/function.strcmp.php
I hope it helps :)
Regards,
SA

Hide HTML with PHP conditional - Not working

I am very new to PHP and I am trying to get a piece of PHP code to run inside of my HTML file.
I have a drop down menu. If users select one item, it should display additional fields. So, I want them to only display if they select that item from the drop down menu. I am trying to select it based on the value for that drop down item. I have not declared any PHP values in a PHP script. This is all in HTML.
I know that with jquery you have to pull in the jquery library before running the script. Do I need to do this with PHP also?
Here is the code that I am trying to run:
Thank you in advance!
<?php
if ($dropmenuValue == "specificParameter") {
?>
<div>
-conditional content-
</div>
<?php
}
?>
<?php
if ($value ) {
?>
<div>
-conditional content-
</div>
<?php
}
?>
If you are setting the $values variable like this
$value = true
Then you can do
<? if($value){ ?>
<div>Content Here</div>
<? } ?>
Is the page a .php page?
A multi conditional statement is done in a different manner. The manner being:
<?php if($val): ?>
<div>
-conditional content-
</div>
<?php endif; ?>
the problem is that your comparing a boolean to a String.That's why your code won't work I would suggest something like If($value){ or if($value==true){.
you want to do if($value == true). The quotes you have around true does not make it a boolean variable.
Everything else in your code looks find.
tldr: correct: if($value == true) ----------
incorrect: if($value == "true")
<?php if ($value ):?>
<div>
-conditional content-
</div>
<?php endif;?>
Here are a few pointers.
$value is a boolean value. It is best to evaluate using if($value)
The PHP if syntax used above is a much cleaner way.
You will be able to see where your if statement begins and ends.
Enjoy!

PHP while loop not ++'ing variable within if statements

statmentI am currently working on a project. I am having issues with making a variable ++ in the loop while nested in if statements. I really do not understand why it's doing what it's doing. Here is my code.
<?php $i=0;
while ($loop->have_posts() ) : $loop->the_post(); ?>
<?php if(get_field('featured_game') && valid_release(get_field('release_date'))):?>
<div class="item <?php if($i == 0){echo 'active';}?> row carousel-<?=$i;?>">
// do generated html
<style>
.carousel-<?=$i;?>{
// do generated css
}
</style>
</div>
<?php $i++;?>
<?php endif?>
<?php endwhile;?>
</div>
My results have
carousel-
these spots all having returned 0 despite the loop running. meaning that incrment is not happening.
if I remove the if statement the loop works, as expected. The if statement are just to verify criteria to be true. I do can place the ++ outside of the if statement I get the same results.
Could some please explain what I am missing here? This seems like such a basic problem. I really do not understand why $i will not increment when does meet the criteria and posts the correct info. Thanks in advance to anyone who takes the effort.
I ran this code:
<?php $i = 0;
while ($i < 10) : ?>
<?php if (true): ?>
<?php if ($i == 0) {
echo 'active';
} ?>
<?= $i; ?>
<?php $i++; ?>
<?php endif ?>
<?php endwhile; ?>
and the result was:
active 0 1 2 3 4 5 6 7 8 9
so either
get_field('featured_game')
or
valid_release(get_field('release_date'))
must be false.
Try
var_dump(get_field('featured_game'));
var_dump(valid_release(get_field('release_date')));
inside the loop.
Turns out, it was increment properly all along.
My issue turns out to be that bootstraps carousel cycles the the content within the the parent div not the actual div it seems. If I disable it, or look directly at the source, everything is what it is supposed to be.

If the input is empty, how do I display something else with PHP?

My WordPress options panel has a section where the user can paste their logo's URL to show up in the header. If the input is blank, I want the Blog's title to show up instead on my header. The ID of the input is "nl_logo", so I added an if statement in my header.
<?php if ("nl_logo") { ?>
<img src="<?php echo get_option('nl_logo'); ?>">
<?php } else { ?>
<h1><?php bloginfo('name'); ?></h1>
<?php } ?>
The first part of the if statement works. However, anything below else doesn't work when I have no URL saved in my input. So, if the input is empty, how do I display something else with PHP? Or is there a different and better way to do this? For example, creating a function and calling the results to display with a simple line of PHP?
Try this... also try to understand it.
Keeping with the established coding style:
<?php $nlLogo = get_option('nl_logo'); ?>
<?php if (empty($nlLogo)) { ?>
<h1><?php echo(bloginfo('name')); ?></h1>
<?php } else { ?>
<img src="<?php echo($nlLogo); ?>">
<?php } ?>
That should atleast be valid PHP now. I don't know if the functions you are using are correct, but if they are this should work.
Here is a cleaner way to do it...
<?php
$nlLogo = get_option('nl_logo');
if (empty($nlLogo)) {
echo('<h1>'.bloginfo('name').'</h1>');
} else {
echo('<img src="'.$nlLogo.'">');
}
?>
Option three because I'm feeling "teachy" using a ternary. Probably a little long for this to be the best choice, but it is another option.
<?php
$nlLogo = get_option('nl_logo');
echo(empty($nlLogo) ? '<h1>'.bloginfo('name').'</h1>' : '<img src="'.$nlLogo.'">');
?>
Note I switched the if / else because I'm using empty and it just feels cleaner to do it this way instead of using !empty()
<h1><?php bloginfo('name'); ?></h1>
Should be
<h1><?php echo bloginfo('name'); ?></h1>
You could try the empty method to test if a string is empty. In context:
if(!empty($nl_logo)) {
// stuff
} else {
// other stuff
}
This does not make sense:
if ("nl_logo")
You're basically saying if the string exists then proceed, which it does, of course.
It makes more sense to take the input string:
$input = $_POST["postedInput"];
As an example, doesn't really matter as long as you know how you got the value into $input.
Now, you can use the ternary operator to determine whether you want to use the user's input or if you want to use the default title:
$img = $input == "" ? bloginfo($input) : get_option($input);
Depending on what your functions do.. if get_options returns a string then this will work.
Anyway, don't mis PHP and HTML, it will make things complicated and you'll be locked into bad design.
Note:
Make sure to check if the input is actually received, using isset.
You are testing for string "nl_logo" to be true. That returns always true.
try changing your code like this:
<?php
$nl_logo = get_option('nl_logo');
if (!empty($nl_logo)):
?>
<img src="<?php echo $nl_logo; ?>">
<?php else: ?>
<h1><?php bloginfo('name'); ?></h1>
<?php endif; ?>
Don't close the php tags.
Whatever html you need to write, just write it as echo statements within one big php block.
This should fix your problem

Categories