IF statement not running in PHP
I have a code to declare a variable and then an IF state开发者_如何转开发ment 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?
<?php if ( $contents = 10 ) {
should be
<?php if ( $contents == 10 ) {
Don't worry, it's a common mistake :)
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
}
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 '='
精彩评论