Else statement not executing in php - php

My code always executes if statement, even if the condition is false, it doesn't go to else.
<?php
$link = $count;
if ($link == 8 || 10) {
echo "<a href='files/".$link.".pdf'>Link</a>";
} else {
echo "Contact HES sales representative for detailed layout model";
}
?>

Because 10 is a "truthy" value, the condition will always be true. You basically have
if($link == 8 || true) {
because 10 == true is, in fact, true.
You should adapt it to either
if ($link == 8 || $link == 10) {
or you can use in_array() if you start to get many values
if (in_array($link, array(8, 10)) {
If you want, you can use strict comparison - if (and only if) $link is an integer. Then you'd have three equalities, which requires the same value and the same type. This is because PHP is weakly typed, so it doesn't compare types by default (and as a result you can compare different types and have a valid result). Using strict comparison allows you to better control what type of variables you compare.
if ($link === 8 || $link === 10) {
Proof that 10 == true
in_array()
Comparison operators in PHP
The 3 different equals

The condition $link == 8 || 10 will always return true. If $link isn't 8, then it checks if 10 is true. Any non-zero value is true.
Instead:
if ($link == 8 || $link == 10) ...
Or if you prefer to check a value in a list:
if (in_array($link, [8, 10])) ...

if($link == 8 || 10)
// this statement will always be true
because 10 is a non-zero which is asserted as true.
you can do like this if($link == 8 || $link == 10) to get this working

You need to modify your if part you are defining your if wrong
if ($link == 8 || $link == 10) {
echo "<a href='files/".$link.".pdf'>Link</a>";}
} else {
echo "Contact HES sales representative for detailed layout model";
}

Related

PHP multiple OR logical operators in one IF statement

I have a question about IF statements with multiple logical OR operators.
If we let:
$x=1;
A. I typical would write a IF statement comparing two items like this:
if($x == 1 || $x == 2) echo 'good';
else echo 'bad';
B. But, is this a valid IF statement? If not, why? (because it seems to work)
if($x == (1 || 2)) echo 'good';
else echo 'bad';
C. I typical would write a third comparison like this:
if($x == 1 || $x == 2 || $x == 3) echo 'good';
else echo 'bad';
D. What about this, following suit with B, above? (it does not seem to work)
if($x == (1 || 2 || 3)) echo 'good';
else echo 'bad';
The example in B, above works, but not the example in D. Why?
I cannot find any PHP documentation as to why.
Here is what happens for every version:
A. $x == 1 || $x == 2
PHP will compare $x with the value 1, this is true so it can short-circuit the if and echo 'good'.
B. $x == (1 || 2)
PHP will evaluate 1 || 2 because parentheses indicate the priority, as the result should be a boolean expression it will cast 1 to a boolean which evaluates to true so the expression becomes $x == true.
Now PHP will evaluate this expression. First it will cast both types to the same, according to the documentation, it will "Convert both sides to bool". So, same as above, as $x is 1 it will be cast to true and then the expression becomes true == true which is true.
C. $x == 1 || $x == 2 || $x == 3
It is the same as A.
D. $x == (1 || 2 || 3)
It is quite the same as B.
And, for the record 1 == (1 || 2 || 3) evaluates to true.

Is there a way to state multiple conditions associated with another condition as a whole?

I am trying to consolidate a few different if statements. What I am trying to accomplish would read something like this:
If (this is true and this is true) OR (this is true and this is true) AND (This is true)
So, one at least one of the first two sets of parentheses would need to be true, and if one of those is true, then also the last set of parentheses would need to be true, in order for the code inside to be executed.
Here is the specific code I am (unsuccessfully) trying to make work:
if(($calc->number % 2 == 1 && $calc->doubleColor == 'b2' | $calc->number % 2 == 0 && $calc->doubleColor = 'r2') && in_array($calc->number, $backToBet)){
}
Is there a way to do this? A possibility? Is there any drawback to getting a lot into a single if statement?
EDIT
$blackMatch = $calc->number % 2 == 1 && $calc->doubleColor == 'b2';
$redMatch = $calc->number % 2 == 0 && $calc->doubleColor = 'r2';
$numberMatch = in_array($calc->number, $backToBet);
if(($blackMatch || $redMatch) && $numberMatch){
}
/ ** Calc->number = 2, $blackMatch = false, $redMatch = false,
$numberMatch array contains 2 **/
Basically what I end with is a 'true' result, even though neither of the conditions within the inner parentheses are satisfied.
to make code easier to read, I'd suggest to use separate variables, like this:
$condition1 = ($calc->number % 2 == 1) && ($calc->doubleColor == 'b2');
$condition2 = ($calc->number % 2 == 0) && ($calc->doubleColor == 'r2');
$condition3 = in_array($calc->number, $backToBet);
if (($condition1 || $condition2) && $condition3) {
}
two things to note:
|| is logical OR, | is bitwise OR
== is comparison, = is assignment

Add multiple condition in if statement [duplicate]

This question already has answers here:
Checking string length with strlen
(3 answers)
Closed 9 years ago.
I want to add 2 numbers in the strlen command. here is my php code:
$name = mysql_real_escape_string($_POST['dgt']);
if(strlen($name) != "32") {
print "This is not a name.";
} else {
It checks if the length is 32. I want it to check if the length is 32 OR 40. how can I do that?
First of all, don't use mysql_real_escape_string(); the old mysql_ API is deprecated, so consider switching to PDO or mysqli instead.
Second, you should consider using input filtering; $_POST['dgt'] may not exist at all, so use filter_input().
Third, you should use numeric values to compare against the output of strlen(); although PHP will treat "32" as a number, it's better to be explicit.
Lastly, if a name must be either 32 or 40 long, you can simply add the condition:
$name = filter_input(INPUT_POST, 'dgt', FILTER_UNSAFE_RAW);
if (empty($name) || (strlen($name) != 32 && strlen($name) != 40)) {
print "This is not a name.";
}
Alternatively, use in_array():
if (empty($name) || !in_array(strlen($name), array(32, 40))) {
print "This is not a name.";
}
Use the and operator "&&" in your conditional, like the code below.
if(strlen($name) != 32 && strlen($name) != 40)
If you would like it to check if name is length 32 or 40 then use the or operator "||" like the code below.
if(strlen($name) == 32 || strlen($name) == 40)
user2910265 has a good point, assign the return value of strlen() to a variable so that only one call is made, like so.
$length = strlen($name);
if(!($length == 32 || $length == 40))
print "this is not a name.";
} else {
From the PHP: Logical Operators - Manual, you want to use either
or
|| (this form has higher precedence)
$a or $b Or TRUE if either $a or $b is TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
So, you could use something like this
$len = strlen($name); // just get the length once and then
// use it to compare however many times....
if (!($len == 32 or $len == 40))

Simple "== x OR y" in PHP

I have a loop in which I check for numbers. Something like this, more or less:
<?php $counter = 0; ?>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php $counter++; ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php if ($counter == (2 || 4)) : ?>
// DO SOMETHING
<?php endif; // counter ?>
...
But $counter ==(2||4) returns true for every number (1, 2, 3, 4 etc.). I also tried:
$counter == 2 || 4
$counter === 2 || 4
$counter == (2 or 4)
But to no avail. The first and last one also return true for every natural number and the second one never returns true.
An alternate solution would be to do the following:
$allowed = array(2, 4);
if (in_array($counter, $allowed)) {
// good value
}
The advantage of this is that you can extend the list of allowed values very easily, maybe even placing them in an external config.
simply replace
if ($counter == (2 || 4)) :
with
if ($counter == 2 || $counter == 4) :
see also the manual: http://www.php.net/manual/en/control-structures.if.php
If you want to do something when the counter is even, you can use the following:
<?php if ($counter % 2 === 0) : ?>
// do something
// will match 0, 2, 4, 6, ...
<?php endif; ?>
Its not possible to check for multiple values inside a condition like that.
This is one reason why php sucks... you're are forced to use two conditions, like
if($counter == 2 || $counter == 4)
or if you want to trigger your conditions on even numbers
if($counter % 2 == 0)
someone mentioned in_array() but you should know that arrays are very expensive in php in terms of resources.
The expression (2 || 4) will always return true. This is because both operands to the || operator are non zero valued constants. It is essentially equivalent to (true || true) which is always true as is (false || true).
the expression
$counter == (2 || 4)
will yield true except when $counter is 0
You want to write
($counter === 2 || $counter === 4)
note that you should always use === instead of == because the latter performs type coercion on its operands.

PHP Elseif Ternary Operators

I am trying to convert the following code into a Ternary Operator, but it is not working and I am unsure why. I think my problem is that I do not know how to express the elseif operation in ternary format. From my understanding and elseif is performed the same way as an if operation by using the format : (condition) ? 'result'.
if ($i == 0) {
$top = '<div class="active item">';
} elseif ($i % 5 == 0) {
$top = '<div class="item">';
} else {
$top = '';
}
$top = ($i == 0) ? '<div class="active item">' : ($i % 5 == 0) ? '<div class="item">' : '';
$top = ($i == 0) ? '<div class="active item">' : (($i % 5 == 0) ? '<div class="item">' : '');
you need to add parenthesis' around the entire else block
The Ternary Operator doesn't support a true if... else if... else... operation; however, you can simulate the behavior by using the following technique
var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
I personally don't care for this as I don't find it more readable or elegant. I typically prefer the switch statement.
switch (variable) {
case 1 : name = 'foo'; break;
case 2 : name = 'bar'; break;
default : name = 'bas'; break;
}
Too late probably to share some views, but nevertheless :)
Use if - else if - else for a limited number of evaluations. Personally I prefer to use if - else if - else when number of comparisons are less than 5.
Use switch-case where number of evaluations are more. Personally I prefer switch-case where cases are more than 5.
Use ternary where a single comparison is under consideration (or a single comparison when looping), or when a if-else compare is needed inside the "case" clause of a switch structure.
Using ternary is faster when comparing while looping over a very large data set.
IMHO Its finally the developer who decides the trade off equation between code readability and performance and that in turn decides what out of, ternary vs. if else-if else vs. switch-case, can be used in any particular situation.
//Use this format before reducing the expression to one liner
$var=4; //Change value to test
echo "Format result: ";
echo($var === 1) ? 'one' : //if NB.=> $varname = || echo || print || var_dump(ternary statement inside); can only be (placed at the start/wrapping) of the statement.
(($var === 2) ? 'two' : //elseif
(($var === 3) ? 'three' : //elseif
(($var === 4) ? 'four' : //elseif
'false' //else
))); //extra tip: closing brackets = totalnumber of conditions - 1
// Then echo($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false')));
echo "<br/>";
var_dump("Short result: ", ($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false'))) );

Categories