PHP Type Casting

Sat, 10 Jul 2010

I was playing around with Type Casting in PHP, and all the results seem to be expected except for the last ones which is actually comparing the ASCII values, it is not comparing the string length, nor is it comparing the total of all the ASCII characters added up, only the first one.

In ASCII capital letters come before lowercase, so A = 65, B = 66, and going down the line, a = 97, b = 98. Type Casting
echo (int) 5;		// Output: 5
echo (int) 5.5;		// Output: 5

echo (float) 5.5;	// Output: 5.5 (use: float, double, real)

echo (bool) 5.5;	// Output: 1 (for true)
echo (bool) 0;		// Output: NULL (for false)

echo (string) 123;	// Output: 123
echo (string) "test";	// Output: test

echo (array) "test";	// Output: Array( 0 => 'test');

echo (int) (7 > 5);	// Output: 1, ie: Calculates as true, outputs 1, 
			// (int) doesn't do anything in this scenario since true
			// outputs as 1;

echo (int) (5 > 6);	// Output: 0, ie: Calculates as false, result is false, 
			// (int) turns false into 0;

echo (int) ('CAT' > 'DOG');	// Output: false, The letter D is a higher value and C
echo (int) ('pig' > 'Pig');	// Output: true, The letter p is a higher ASCII value than P


Practical Example of Type Casting This is a very plain example and putting all normal security aside -- Let's say you have someone go to a page of your that passes a variable, and it only reads digits:
http://yoursite/index.php?id=44. 
Lets assume id is passed into a Database Query. If someone types:
 http://yoursite/index.php?id=fish
it is going to pass the query with text. So you could say,
$id = (int) $_REQUEST['id']; 
The id will return 0 for false if the string contains text. That way you won't get any SQL errors searching a digit field with text.