There is probably a very simple fix to this, but i'm all new with php, and very ignorant. I've been trying to get my head around this problem, but to no avail. Here is the code :
echo $slot['slot_type'];
echo "<br><br>";
if ($slot['slot_type']='tree') echo "This place is full of life, and can be used for hunting, gathering, logging, or other activities.";
if ($slot['slot_type']='town_hall') echo "The town hall houses the governors, and is propriety of the King.";
if ($slot['slot_type']='farm1') echo "Townspeople attempt to grow a selection of wild plants on these crops, hoping for a steady food supply.";
if ($slot['slot_type']='farm2') echo "Farming is hard work, but a full storehouse of food is a great comfort.";
The first line with echo $slot['slot_type'];
was my attempt to try and understand why my "if" statement does not work. However, it prints the proper string, in this case "tree".
So, in practise, instead of printing one of the proposed text strings, the browser prints all four of them, as if it ignored my IF statements completely. Again, sorry for asking what looks like such a silly question.
You need to change all your single =
to ==
or some other logical check.
What you are essentially doing is assigning $slot['slot_type']
the values on the right hand side of your condition which will always return true.
Have a read of the php manual here http://uk.php.net/manual/en/language.operators.php
As an aside, your if
structures might be better created using a switch
statement.
You need to use it like this:
if ($slot['slot_type']=='tree')
You are inserting the values into $slot['slot_type']
instead of comparing.
You're using the assignment operator, =
, in your if
statements. You should be using the comparison operator, ==
.
An elaboration on how this works: the if
statement will evaluate the condition given to see if it matches. With your current assignment operator, the PHP engine will actually complete that command (that is, assign the value tree
to your slot_type
), which returns true since the command successfully completed. The rest of the if
statement then executes. The same happens for the rest of the if
statements (because you're re-assigning values to your slot_type
without error), which then also executes the other branches.
My take: always have php.net open in a tab:
http://uk3.php.net/manual/en/language.operators.assignment.php
http://uk3.php.net/manual/en/language.operators.comparison.php
CASE 1: = (assignment)
$var = 'hello';
CASE 2: ==
equality after type juggling
if(0 == "a") {
print("hi");
}
* will print "hi" because string "a" will actually be converted to 0 by PHP
CASE 3: ===
testing for identity (types must be the same)
if(0 === "a"){
print("hi");
}
* will not print "hi" because the two operands are obviously not the same type.
In your case, you want case 2, to test for equality, or you could use case 3.
Change = to == . This: = is ony for giving variable value (assignment), and this == is for comparing it with something.