Saturday, April 6, 2013

XOR in Loosely type Language (PHP)

Recent days, i have to perform exclusive OR (XOR) operation between two numbers. One of them is Hex. and other one is in decimal i.e. in base 10. In PHP, we use ^ operator to perform exclusive OR operation.

Just for reminder, in XOR we get true if and only if exactly one of two bit is true. For further clarification look at below truth table:


ABA xor B
TTF
TFT
FTT
FFF

Now, consider we have to xor F(15 in base 10) with 8. The answer should be 7. I write following code in PHP to do this:
echo "F" ^ "8";
The answer would not be 7. Why? In fact, here, PHP is taking the ascii value of "F" and "8" and then performing xor in between those ascii value.

Now if we have to do correct xor then use following code:
echo 0xF ^ 8;

In fact, above example is too much simple. One may ask if we know a number then why we should cast it to string and then perform xor operation? The answer is simple, in many cases we have to read the numbers from some other stream like network or input etc. There most of the time we get string and PHP does not know "F" in a string is Hex. or it is a character. We can use dechex and hexdec functions in PHP for conversion in these cases

Tuesday, April 2, 2013

PHP: Sorting array on a nth level key

PHP has very handy functions to sort arrays e.g. sort. A simple use of this can be as follows:
$arr = array(5,4,1,2);
sort($arr)
print_r($arr);
Now what if we have to sort array on keys? We can use ksort function. For example, consider following code:
$arr = array("y" => "second", "x" => "first", "z" => "third");
ksort($arr);
print_r($arr);
 Now we made example a bit complicate. Consider we have following array:
$arr = array( 0 => array("name" => "w3", "city" => "city3"),
                      1=> array("name" => "w1", "city" => "city1") ,
                      2 => array("name" => "w2", "city" => "city2") ,
            );
Now we want to sort this array on the basis of name. To achieve this one may use the loops. But I found very simple solution of this one. Use usort. Take a look at following code. It will sort array on the basis of name:

function mySort($a, $b)
{
    return strcasecmp($a['name'], $b['name']);
}

usort($arr, "mySort");

echo "<pre>";
print_r($arr);
Now what if we want to sort array first on name and then on city. It is same as we use ORDER BY clause in SQL. We can easily achieve this by following code:

function mySort($a, $b)
{
    if(strcasecmp($a['name'], $b['name']) == 0)
    {
        return strcasecmp($a['city'], $b['city']);
    }
   
    return strcasecmp($a['name'], $b['name']);
}
 
Now by using above technique we can sort on nth level.