0

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";
}
?>
Qirel
  • 25,449
  • 7
  • 45
  • 62
veenu
  • 53
  • 1
  • 2
  • 9

4 Answers4

4

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) {
Qirel
  • 25,449
  • 7
  • 45
  • 62
1

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])) ...
Matt S
  • 14,976
  • 6
  • 57
  • 76
1
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

FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
0

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";
}
Muhammad Usman
  • 1,403
  • 13
  • 24