I have seen this on some posts:
$num = "5";
if(((int)$num) < 4){ ...}
is there a reason to cast "5" as an int or is it just as good to say:
if($num < 4){ ...}
because i have tested it with my code:
echo $num + 4; //outputs 9
echo (int)$num + 4;//also outputs 9
Update: My question is about casting in general, the above are just one or two examples.
Update 2: right off type juggling manual php
<?php
$foo = "0"; // $foo is string (ASCII 48)
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)
?>
^^^^ why do those last 2 things happen?
In the cases you have mentioned, there is no really good reason. This is because, not only is PHP a dynamically typed language, the operators being used are not type sensitive.
However, casting has many good uses as well. In the case of (int)
you could cast to ensure that you are always using a integer during your operations. Also, by casting ahead of time, you save PHP from having to continually type juggle later on.
Edit due to question edit (rev4)
The last two items happen because PHP will try to force a string into an integer during a math operation. Thus, it parses the string out as a number. Once it fails to find a valid integer, the number(s) found are returned.
Basically, from the beginning of the string, find anything that matches the integer/float numbering format. As soon as something STOPS matching that format, return what you have. If the first character cannot match the format, return 0;
.
For a better explaination, read: http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting
Everything I've read here sounds perfectly reasonable, so I won't rehash it. Instead, I'll give you two examples of where I use type casting in PHP pretty often:
Providing an API and trying to return proper types in various formats generally requires explicitly typing every return value. For example, if I'm returning some mixed array of data through XML_Serializer or XML-RPC and I don't cast my ints/floats properly, they will be returned as strings which causes all number of issue for folks using strongly typed languages trying to consume the API. I can't, however, speak to how SOAP+WSDL would handle that since I haven't messed with it.
Casting returned values to arrays in cases where a library (or our code) returns either an array or null and we can't/don't want to modify it. That's typically solely to prevent the warnings you get when a non-array is passed to an array control struct or method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With