Changes

Jump to: navigation, search

PHP Operators

984 bytes added, 15:32, 30 May 2007
Concatenation of Numbers and Strings in PHP
<tt>11 is my lucky number</tt>
 
it is important to note an issue when dealing with strings and numbers. While the above works fine because we began the expression with the addition something different happens when we have the addition afer the string:
 
<pre>
echo 'My Lucky number is ' . 6 + 5;
</pre>
 
The above will produce unexpected results (typically it will output a number such as 5). The reason for this is because we have asked PHP to take a string (My Luck number is ), append the number 6 to it (to produce My Luck number is 6) and then final ''arithmetically'' add the number 5 to the string (wihch doesn't make a lot of sense). To resolve this issue we need to tell the PHP pre-processor to perform the addition (6 + 5) ''before'' performing the concatenation. We can achieve thjis by surrounding the addition expressoin in parentheses ''( and )''. Therefore the modified script:
 
<pre>
echo 'My Lucky number is ' . (6 + 5);
</pre>
 
will now produce the desired output:
 
<tt>My Lucky number is 11</tt>

Navigation menu