views:

49

answers:

3

I have a code to declare a variable and then an IF statement which uses that variable to either display, or not display an image.

This code is before HTML

<?php $contents = file("textdocument.txt") ?>

This code is in the HTML

<?php if ( $contents = 10 ) { 
echo '<img src="image.png" name="image" border="0">'; }
else {echo "wrong number"; } ?>

The problem I get is no matter what the number is, the image always displays. Do you guys have any solutions for this?

+9  A: 
<?php if ( $contents = 10 ) { 

should be

<?php if ( $contents == 10 ) { 

Don't worry, it's a common mistake :)

Eric Petroelje
I recommend reversing these checks so it doesn't happen and it throws an error -- use `if ( 10 == $contents ) {` instead, and there will never be any chance of accidentally assigning the value to the variable.
Nathan Loding
I tried this however now it just says "wrong number". Am I making another mistake?
Tony C
alter `file(..)` to `trim(file_get_contents(..))`
Wrikken
building on that:`if (intval(file_get_contents(..)) === 10) {`
Jayrox
Rather than reversing the check as suggest by Nathan Loding, get into the habit of paying closer attention when using comparison operators. You will usually **not** be comparing to a literal but rather variable to variable, i.e., `($a == $b)` where reversing helps nothing.
webbiedave
Thanks Jayrox, your code worked!
Tony C
+2  A: 

When you have a single =, you are performing an assignment on that variable. And that expression ends up being the value you stored to the variable. So, if ($contents = 10) is basically the same as if (10) (which is always "true" in PHP)

You need to use a comparison operator, such as == to compare the value of $contents with the value you are looking for. (ie. 10)

Also, the function file returns an array, with each value of that array corresponding to 1 line of the file. So, you either need to use file_get_contents to return everything as a single string, or reference the particular line of that file as the index of the array.

// Using file()
$contents = file("textdocument.txt");
if ($contents[0] == 10) {
    // If the contents of the first line of the file is '10', do something
}

// Using file_get_contents()
$contents = file_get_contents("textdocument.txt");
if ($contents == 10) {
    // If the contents of the entire file is '10', do something
}
Dominic Barnes
+1  A: 

As stated above, your "=" should be replaced with "==".

A good habit to get into to avoid this type of mistake in the future is to swap the order of the comparison, as in:

if(10 == $contents)

This way, if you mistakenly use the assignment operator in place of the comparison, it will result in an error, rather than a tough-to-spot bug:

Parse error: syntax error, unexpected '='
Clayton