Newbie question: Why is my PHP OR operator not working? - php

I have a function where I want to display something if the value equals A, C or D.
The problem is if the value is set at B or E, the function is display data in the A.C.D. set in addition to the B or E set.
What am I doing wrong?
$linkp = opensky_featured_image_position();
if ( $linkp == 'featuredimg-1' || 'featuredimg-3' || 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
if ( $linkp == 'featuredimg-2' ) {
echo '<h1>L - '. opensky_featured_image_position() .'</h1>';
}
if ( $linkp == 'featuredimg-5' ) {
echo '<h1>N - '. opensky_featured_image_position() .'</h1>';
}

if ( $linkp == 'featuredimg-1' || 'featuredimg-3' || 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
Should be
if ( $linkp == 'featuredimg-1' || $linkp == 'featuredimg-3' || $linkp == 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
If all the values of $linkkp are defined you could do something like this
$linkArr = array(
'featuredimg-1' => 'F',
'featuredimg-2' => 'L',
'featuredimg-3' => 'F',
'featuredimg-4' => 'F',
'featuredimg-5' => 'N',
);
$linkp = opensky_featured_image_position();
echo '<h1>'.$linkArr[$linkp].' - '. opensky_featured_image_position() .'</h1>';

It's all about operator precedence. Since == is with higher precedence, your code is rewritten as follows:
if ( ($linkp == 'featuredimg-1') || 'featuredimg-3' || 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
which turns to be
if ( false || true || true ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
Since when you cast a non-empty string to bool, it will be evaluated as true.
You have to rewrite it:
if ( $linkp == 'featuredimg-1' || $linkp == 'featuredimg-3' || $linkp == 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
Which is equalent to:
if ( ($linkp == 'featuredimg-1') || ($linkp == 'featuredimg-3') || ($linkp == 'featuredimg-4') ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
But when you are dealing with such condition, maybe it's better to use in_array

For me this looks like that you're making too much use of if to describe something very simple: Certain values map to characters, that is essentially static data. No need to use so much verbose code to write that data into your code.
Consider using arrays instead to get the character you're actually looking for based on the number and then just echo it afterwards:
$linkp = opensky_featured_image_position();
sscanf($linkp, 'featuredimg-%d', $number);
$chars = 'FLN';
$map = array(1 => 0, 2 => 1, 3 => 0, 4 => 0, 5 => 2);
echo '<h1>', $chars[$map[$number]], ' - ', $linkp, '</h1>';
Demo

It should be:
if ( $linkp == 'featuredimg-1' || $linkp == 'featuredimg-3' || $linkp == 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}
..

'featuredimg-3' will always be evaluated as true, you have to try $linkp == 'whatever' in each or subcondition.
so :
if ( $linkp == 'featuredimg-1' || $linkp == 'featuredimg-3' || $linkp == 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
}

You'll need to specify the == operator for each condition in the or clause, otherwise, the string values such as 'featuredimg-3' will be evaluated on their own, and any non-empty string evaluates to true.
Also, when the choices are mutually exclusive, it is better to use elseif so that PHP can skip the remaining if statements when it matches one.
I've also added a final else, so you can see how you can do something in case none of the values match.
$linkp = opensky_featured_image_position();
if ( $linkp == 'featuredimg-1' ||
$linkp == 'featuredimg-3' ||
$linkp == 'featuredimg-4' ) {
echo '<h1>F - '. opensky_featured_image_position() .'</h1>';
} elseif ( $linkp == 'featuredimg-2' ) {
echo '<h1>L - '. opensky_featured_image_position() .'</h1>';
} elseif ( $linkp == 'featuredimg-5' ) {
echo '<h1>N - '. opensky_featured_image_position() .'</h1>';
} else {
echo '<h1>Invalid or missing image position</h1>';
}
You may also want to take a look at the switch/case structure.
Using arrays as others have suggested does allow for brevity and arguably readability. If you do use arrays, you may still need to check to ensure that you find a value in the array and handle the case if you don't.

Related

PHP: Echoing HTML When Multiple Checkboxes Options Are Checked

I've edited this question, because I felt I needed to be clearer in my request.
The code below relates to options checked in a checkbox. It will echo 'both values' when they are both checked, and it will echo 'only valueA', I cannot get it to echo 'only valueB' which instead prints blankly with no echo. Thoughts?
<?php
if (( $a == "General" ) && ( $b == "Specialist" )) {
echo '<h2>both values are printed in HTML</h2>';
}
?>
<?php
if (( $a == "General" ) && ( $b != "Specialist" )){
echo '<h2>only valueA is printed in HTML</h2>';
}
?>
<?php
if (( $a != "General" ) && ( $b == "Specialist" )) {
echo '<h2>only valueB is printed in HTML</h2>';
}
?>
If you want to check whether a value is in array you should use in_array function. Your code should look like this:
<?php
$CheckBox = $form_data['field'][1]
$a = ( "valueA");
$b = ( "valueB");
$isAChecked = in_array($a, $CheckBox[1]);
$isBChecked = in_array($b, $CheckBox[1]);
?>
<?php
if ( $isAChecked && $isBChecked ) {
echo '<h2>both values are printed in HTML</h2>';
} else if ( $isAChecked ) {
echo '<h2>only valueA is printed in HTML</h2>';
} else if ( $isBChecked ) {
echo '<h2>only valueB is printed in HTML</h2>';
} else {
echo '<h2>nothing printed</h2>'
}
?>

if else statement, not outputting else if?

I have a small if else statement, where the if gets output, but not the else currently? I tried double pipe, but no luck.
I have a variable set at the top of my page -
$portfolio_style = ( isset( $uno_theme['portfolio-style-select'] ) ? $uno_theme['portfolio-style-select'] : null );
And then my if else which will not work -
<?php if ( $portfolio_style == 'portfolio_style_one' || 'portfolio_style_two' ) { ?>
<div class="grid">
<?php } elseif ( $portfolio_style == 'portfolio_style_three' ) { ?>
<div class="wfull">
<?php } ?>
I want it where if portfolio style one or two has been selected, show class 'grid', else if style three has been selected show class 'wfull'
Could I also refine this piece of code at all? -
$portfolio_style = ( isset( $uno_theme['portfolio-style-select'] ) ? $uno_theme['portfolio-style-select'] : null );
Many thanks
You cannot omit $portfolio_style variable after || because otherwise the sole string 'portfolio_style_two' will always evaluate as true as stated in the manual describing conversion to boolean:
Your code should be this:
<?php if ( $portfolio_style == 'portfolio_style_one' || $portfolio_style == 'portfolio_style_two' ) { ?>
<div class="grid">
<?php } elseif ( $portfolio_style == 'portfolio_style_three' ) { ?>
<div class="wfull">
<?php } ?>
Try to change the if condition:
<?php if ( $portfolio_style == 'portfolio_style_one' || $portfolio_style == 'portfolio_style_two' ) { ?>
you need to change this line as
if ( $portfolio_style == 'portfolio_style_one' || $portfolio_style == 'portfolio_style_two' )
Try this:
echo ($portfolio_style == 'portfolio_style_one' || $portfolio_style == 'portfolio_style_two') ? '<div class="grid">' : (($portfolio_style == 'portfolio_style_three' ) ? '<div class="wfull">' : '');

PHP how can I optimize this ? many if conditions strpos

I have the following code which checks if some variables contain some specific words.
I'm sure there is a way to really shorter this. I'm a total noob so I can't know for sure how I can optimise this piece of code. Any help would be great..!
<?php
if (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'word') !== false)) {
echo "Doh";
} elseif (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'wurd') !== false)) {
echo "Bam";
} elseif (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'ward') !== false)) {
echo "Yes";
} elseif (in_array(1259, $_product->getCategoryIds()) && (strpos($fabriquant,'wierd') !== false)) {
echo "No";
}
endif;
?>
if (in_array(1259, $_product->getCategoryIds())) {
$words = array(
'word' => 'Doh',
'wurd' => 'Bam',
'ward' => 'Yes',
'wierd' => 'No',
);
foreach ($words as $word => $message) {
if (false !== strpos($fabriquant, $word)) {
echo $message;
break;
}
}
}
A first optimization could be to do nested if statements:
if (in_array(1259, $_product->getCategoryIds()) {
if(strpos($fabriquant,'wurd') !== false) {
} elseif ....
}
Then you shold test for the most likely condiction as the first check, then the second most likely condition and so on ...
Because all the if blocks have a common component, it would be good to extract it and only test it once. The other unique points can be checked individually.
if ( in_array(1259, $_product->getCategoryIds()) )
{
if ( strpos($fabriquant,'word') !== false ) {
echo "Doh";
} elseif ( strpos($fabriquant,'wurd') !== false ) {
echo "Bam";
} elseif ( strpos($fabriquant,'ward') !== false ) {
echo "Yes";
} elseif ( strpos($fabriquant,'wierd') !== false ) {
echo "No";
}
}

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.

Simple PHP Condition help: if($Var1 = in list($List) and $Cond2) - Is this posslbe?

Is this a possible function?
I need to check if a variable is existent in a list of ones I need to check against and also that cond2 is true
eg
if($row['name'] == ("1" || "2" || "3") && $Cond2){
doThis();
}
It's not working for me and all I changed in the copy paste was my list and the variable names
if(in_array($row['name'], array('1', '2', '3')) && $Cond2) {
doThis();
}
PHP's in_array() docs: http://us.php.net/manual/en/function.in-array.php
You're lookin for the function in_array().
if (in_array($row['name'], array(1, 2, 3)) && $cond2) {
#...
if (in_array($name , array( 'Alice' , 'Bob' , 'Charlie')) && $condition2 ) {
/* */
}
use in_array function
if(in_array($row['name'], array(1,2,3)) && $cond2){
do ...
}
$name = $row['name'];
if (($name == "1" || $name == "2" || $name == "3") && $cond2)
{
doThis();
}
I have something simpler than that, if it's still possible...
if(strpos("1,2,3", $row['name']) !== false) && $Cond2) {
doThis();
}

Categories