PHP Operators

The operators in PHP work similarly to the way that operators work in other languages. Basically there is the same range of arithmetical, string, comparison, logical, and bit operators that other languages have with just a few minor differences.

As many people coming the PHP for the first time will have some exposure to JavaScript, I'll point out several of the main differences in the way that operators work between JavaScript and PHP.

In JavaScript the + operator is used both for addition of numbers and for concatenation of strings (with the latter taking priority if either operand is a string). PHP uses the + operator only for addition and uses a different operator . (dot) for concatenation. Therefore any operations in PHP involving the + operator are always considered to be addition and if either or both of the operands are strings then they will be automatically converted to numbers and added together in PHP instead of being concatenated as they would be in JavaScript.

This conversion of strings to numbers isn't just restricted to the + operator however. In PHP any string containing a number will be automatically converted to a number where possible before applying the operator so where ('2' == '2.00') is false in JavaScript where the a comparison of the two strings is done and they are found to not be equal, in PHP both strings are able to be converted to numbers and so that conversion is done resulting in the two numbers being found to be equal. A comparison that returns false in JavaScript may therefore return true in PHP.

This conversion between different types also has an impact on those values that will be evaluated as false. In JavaScript only an empty string or a numerical zero are considered to be false with all other strings and numbers considered to be true. In PHP the '0' string is also evaluated as false. So where ('0') is true in JavaScript it is false in PHP.

So when processing strings that might contain numbers with PHP you need to be careful to remember that PHP will treat a numeric string as if it were a number and thus may end up processing in a completely different way to JavaScript. Of course if the languages you already knoqw before learning PHP work the same way as PHP with regard to how they handle strings containing numbers then you will have no trouble in understanding how the PHP operations work. In that case the above information will be something to keep in mind if you ever need to write any JavaScript.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow