Page 1 of 1
Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 8:47 am
by becky-atlanta
I take over someone's website. I came across the operator ".=". For example, $a .= "apple". I search this in the php online manual and did not find anything. Should the period be there before the equal sign? I suspect it is not valid because I am getting error that says undefined variable....
If it is a valid code, how to use it properly?
I appreciate your help.
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 8:50 am
by Eran
It's a short hand version which can be used with most operators. The manual does list it -
http://us2.php.net/manual/en/language.o ... string.php
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 10:33 am
by SimonMayer
= will overwrite the existing value of a variable
.= will concatenate to it
I would not recommend you change this syntax unless you have a specific reason to. The previous programmer may have placed it there for a reason.
Code: Select all
$variable = "water";
$variable = "bed";
echo $variable;
will output "bed"
Code: Select all
$variable = "water";
$variable .= "bed";
echo $variable;
will output "waterbed"
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 10:47 am
by jackpf
To avoid the error, define the variable before you use the .= operator.
For example:
Code: Select all
$var = NULL;
//or
$var = '';
//then you can append to it...
$var .= 'something';
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 2:02 pm
by becky-atlanta
Thank you for all your reply, especially Jack's example. It surely helped to fix the error.
Thank you again for helping this newbie out.
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 2:05 pm
by jackpf
Cool, no problem.
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 5:05 pm
by SimonMayer
jackpf wrote:To avoid the error, define the variable before you use the .= operator.
For example:
Code: Select all
$var = NULL;
//or
$var = '';
//then you can append to it...
$var .= 'something';
I have never had to define a variable before using .=
Is this version-specific or controlled by an ini setting?
It would be interesting to know incase I come across it.
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 5:07 pm
by John Cartwright
It will throw a notice using an undefined variable. You should consider turning your error reporting higher to atleast E_ALL.
Re: Is this operator ".=" valid?
Posted: Fri Sep 11, 2009 5:12 pm
by jackpf
I'm sure the .= operator has been around since at least before version 4, if not from the first "real" version.
It's a common operator found in most C style languages. Although obviously with a language specific "concatenation" symbol...in most cases it's a + (addition) symbol...but I guess PHP opted for the . (period).