Skip to content

A Bitwise Operation Pitfall When String Operands Involved in PHP

Normally, PHP will convert string variables which can potentially become a number from the string type to another appropriate types in arithmetic operations. This is because a string cannot be an operand in arithmetic operations, but number can.

You might think the bitwise operations are the same thing, but they are different in some situation. Let's see the following examples to distinguish them.

Here is a very common bitwise operation on number operands.

<?php
$a = 161;
$b = 52;
echo "The Number Bitwise Operation: " . ($a & $b) . "<br />";
?>

The output will be:

The Number Bitwise Operation: 32

This is what we want.

If one of operands is string, PHP will force the string to case into number, so it would be no problem.

<?php
$a = 161;
$b = "52";
echo "The Number Bitwise Operation: " . ($a & $b) . "<br />";
?>

The output will be:

The Number Bitwise Operation: 32

The result is also acceptable.

Sometime, we accidentally or unawarely make both operands strings, PHP considers it's strings-involved operation.

<?php
$a = "161";
$b = "52";
echo "The String Bitwise Operation: " . ($a & $b) . "<br />";
?>

The output will be:

The String Bitwise Operation: 12

You might think it's number bitwise involved, but it's not. This is a bitwise operation on ASCII values of both strings. Since strings bitwise operation is not practical as numbers, so it may not meet your requirement.

A simple trick to make both operands back to numbers is to add 0 on anyone of the operands to force both strings to be casted.

<?php
$a = "161";
$b = "52";
echo "The Number Bitwise Operation: " . ($a+0 & $b) . "<br />";
?>

The output will be:

The Number Bitwise Operation: 32

Now, it's back.

Also, you might be interested in my another post about bitwise in MySQL: How to Retrieve Bit-Typed Values Literally From MySQL.

Leave a Reply

Your email address will not be published.