Sgolds
Sgolds

Reputation: 15

PHP If statement always firing as true

First of all, I know that this has already been asked a million times, but none of the answers I have found seem to work. I have the following if statement in my 'Header.php' page:

<?php
$currentpage = $_SERVER['REQUEST_URI'];
    echo($currentpage);
    if($currentpage == "/recap-2013.php" || "/index.php" ) { ?>
        <script src=... a bunch of HTML
<?php } ?>

The idea is to insert some JS if $currentpage is equal to either recap-2013.php or index.php, and if not, to do nothing.

I've added the echo($currentpage) in there to check what my REQUEST_URI is.

The problem is, even if the request URI is /someotherpage.php, the statement evaluates as true and the JS appears in my head tag. I'm sure it's something small that I'm missing but I cannot figure out what.

Thanks in advance for any help!

Upvotes: 1

Views: 819

Answers (2)

YouSer
YouSer

Reputation: 393

It will always FIRE as true. Why? as you can see, no matter what the outcome of the first condition it will SURELY AND ALWAYS be true at the second...

Okay let's see...

if($currentpage == "/recap-2013.php" || "/index.php" )

So first condition would be:

if($currentpage == "/recap-2013.php")

Let's say the outcome of this would be FALSE.

So let's proceed to the second condition:

if("/index.php")

SURELY and ALWAYS be TRUE!

Why? Because in conditional statements only FALSE(bool), 0, NULL, empty string, etc... are considered to be false. In your situation, "/index.php" is not an empty string nor it is NULL, that is why it is always be TRUE.

As i've understood about your conditions, you are trying to imply:

if($currentpage == "/recap-2013.php" || $currentpage == "/index.php" )

NOTE: Always be careful with conditional statements, it always gets us programmers a lot.

Upvotes: 1

John Conde
John Conde

Reputation: 219864

Your if statement logic is incorrect. What you really mean is:

if($currentpage == "/recap-2013.php" || $currentpage == "/index.php" ) { ?>

In your current logic the second expression will always be true because PHP has loose typing the string will be evaluated as a boolean and a non-empty string is always true.

Upvotes: 6

Related Questions