"if" statement is ignored [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
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 use it like this:
if ($slot['slot_type']=='tree')
You are inserting the values into $slot['slot_type'] instead of comparing.

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'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.

Change = to == . This: = is ony for giving variable value (assignment), and this == is for comparing it with something.

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.

Related

PHP if statement not functioning correctly

I am trying to run an if statment then checks if a cell in database holds a certain value then it sets a variable, if it does not contain that value then it sets a different value
I have tried the following code
case "Chemistry":
$type_tarin_text = ' Exp in ';
if($user_playerdata_tab['profile_type']='Drug Runner') {
$treining_value =$sp_value*11;
} else {
$treining_value =$sp_value*10;
}
$this->AddSubValueByUserID($player_id,'PlayerData','CHEMISTRY_EXP',$treining_value);
break;
It is currently setting the $treining_value as $sp_value*11 regardless of wether profile_type is 'Drug Runner' or not.
Please use == or strict === since you're expecting a string.
You're now assigning a variable which is likely not what you are trying to do.
As others have helpfully pointed out, the issue is here:
$user_playerdata_tab['profile_type']='Drug Runner'
The single = means assignment. What you were intending to do was to test whether the two were equal.
That means using == - or, to be more strict, use === (make that your go-to equality check in the future - you'll thank us later)
Your other assignments are fine, though I would recommend a single space both sides of your = signs for readability

Comparison order in PHP IF

I'm pretty sure that there is no difference between this
if ($value === true)
and this
if (true === $value)
For me it always seems confusing. I used to think that it's a 'bad unconventional style of new developers'. Furthermore, my boss told me never to do such a thing.
But today I was looking through Slim's source code, written by the guy who created PHP: The Right Way, and saw this (line 341).
if (true === $value) {
$c['settings'] = array_merge_recursive($c['settings'], $name);
}
I'm sure a guy like Josh Lockhart wouldn't do something like this if it was considered a bad practice. So what's with this order? Is it some kind of an old tradition?
This is colloquially referred to as 'Yoda Conditions'. The reasoning behind their usage is because sometimes people make mistakes. In the context of an if statement, this is one such mistake that is sometimes made:
if($value = 42)
Notice there is no double equals sign (==). This is a valid statement and is not a syntax error. It is possible that it would cause huge disruptions with the code that follows it, and it is very hard to identify quickly. Yoda conditions get around this by reversing the conditional expression:
if(42 = $value)
This is not a valid statement and is a syntax error, and those are generally reported with a line number included, so they're pretty easy to find.
"Syntax error you have. Line 73 do something else you must." -- Yoda's compiler, probably
Whether or not you actually think they're good or bad is up to personal preference and style. In some cases of popular frameworks (such as Wordpress), Yoda conditions are actually part of the official coding standards. The major critique against them is that, to some, they decrease readability of the code without providing any real major benefit.
As #MonkeyZeus pointed out in a comment to the question, sometimes people do actually mean to only use a single equals sign inside of an if condition:
if($iMustHaveAValue = functionCallThatCanFail()) {
// Rest assured, $iMustHaveAValue has a truthy value.
}
Since the value of an assignment operation is the value assigned, the value that is evaluated by the if condition in this case (and in the original case which was unintended) is whatever value happened to be assigned.

Set variable in if statement expression

I ran across some interesting code today. I tried to find out if this is a feature of PHP or if I am missing something, but was unable to find anything on Google. Probably because I don't know the name of it.
Code
if($logo = \Repositories\Logo::getLogoData($id)){
$logo_href = $logo->link;
}
The variable $logo is not being set anywhere else. It seems like the expression in this if statement is checking to see if the that class method is returning anything and simultaneously setting the variable $logo to be used in the statement.
Is this true? If so, what in the world is this called!?!
You can make an assignment like that in a conditional. What happened logically is that the value is assigned to $logo and then $logo is evaluated as to whether it is truthy. If it is truthy, the code in the conditional executes.
You will oftentimes see this sort of assignment/evaluation in the case of looping through database result sets, but generally I would suggest that it should be avoided outside such a common use case for sake of clarity in reading g code.
Yes, this is a feature. It's like:
$a=$b=5;
But in this case, imagine the bool result of if as var $a.
However, IDE's are used to complain about solutions like this because of == vs. = as a very common possible bug source.

How do I split a numerical query result? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm pulling an id number from a database where it is stored as 12345
When I display it on my page (php), I'd like to have it show up as 1-2345
Can I do this without using Javascript? If so, how?
Thanks!
ETA: it's part of a loop of data that is pulled dynamically, so the number is always different. I need to be able to tell it to put a dash after the first number. It's not necessarily 1-2345; it's more X-XXXX (where X is a random number).
You should be able to use the following in MySQL:
select
concat(left(yourCol, 1),
'-',
right(yourcol, length(yourCol)-1)) YourValue
from yourtable
See SQL Fiddle with Demo
This implements the following MySQL functions:
CONCAT
LEFT
RIGHT
LENGTH
Or you can use SUBSTR instead of RIGHT and LENGTH:
select
concat(left(yourCol, 1),
'-',
substr(yourcol, 2)) YourValue
from yourtable;
See SQL Fiddle with Demo
SUBSTR
In PHP
$id = (str)$dbVal;
$str = $id[0]."-".substr($id, 1, strlen($id) - 1);
echo $str;
$var = "12345";
echo $var[0] . "-" . substr($var,1);
This should work for values of any length.
First, use your SELECT MySQL command to find your ID number.
Let's say $string is actually the 'stringified' version of the ID.
$string = "12345";
$string = str_replace($string[0], $string[0] . "-", $string);
echo $string;
The other answers don't address where to put your code, and why. Inserting a dash after the first digit is display-related logic, and display-related logic belongs in the template. It certainly doesn't belong in the database layer. You could put the actual code right alongside the HTML, but that would be a) probably not very intent-revealing and b) not very reusable.
For the best separation of concerns, I would first define a "helper" function like this, in its own file:
function insert_dash_after_first_number($value)
{
return str_replace($value[0], $value[0].'-', $value);
}
Then, in your template, you can do this (granted you included the helper file):
<?php echo insert_dash_after_first_number('12345'); ?>
Hopefully you can see that separating things in this way would make it pretty clear to others and your future self what's going on. You can just look at the function name and see "oh, this inserts a dash after the first number". You don't have to look at any code and think about what it might do.
$string1 = substr($id, 0,1);
$string2 = substr($id, 1, strlen($id));

PHP: Condition Format - (6 == $var) or ($var == 6)?

I was browsing these PHP Coding Guidelines (a bit outdated but very interesting), and found this:
Condition Format
Always put the constant on the left hand side of an
equality/inequality comparison. For example: if ( 6 == $errorNum ) ...
One reason is that if you leave out one of the = signs, the parser
will find the error for you. A second reason is that it puts the value
you are looking for right up front where you can find it instead of
buried at the end of your expression. It takes a little time to get
used to this format, but then it really gets useful.
I have been using ($var == 6) for years now and the idea of putting them the other way around is horrifying. But as mentioned, this takes a bit time to get used to and is supposed to have clear benefits. We are just writing up standard at our company so if we want to change this, this is the moment to do that. But I'd like to hear if other have experience with this particular format. Any opinions?
EDIT
I am interested in people's experience with making this switch. To me, and most likely to others, this looks like a big change that you need to get used to. But it looks interesting. So the question to those who have switched: can you recommend this change?
6 == $var has a real advantage that $var == 6 does not. There is nothing horrifying about it at all, it just looks different. You should get used to it and use it. In fact, I haven't gotten used to it yet and I forget about it frequently. You really have to think about it and use it since the opposite is so common.
The advantage, in case you didn't know, is to prevent simple syntactical mistakes, thus:
if ($var = 6) {} //weird semantic error
if (6 = $var) {} //parse error

Categories