veenu
veenu

Reputation: 53

Else statement not executing in 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";
}
?>

Upvotes: 0

Views: 306

Answers (4)

Qirel
Qirel

Reputation: 26470

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) {

Upvotes: 4

FULL STACK DEV
FULL STACK DEV

Reputation: 15971

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

Upvotes: 1

Matt S
Matt S

Reputation: 15374

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])) ...

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 1423

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";
}

Upvotes: 0

Related Questions