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?

Comments

Regarding your update, just continue reading: If the last two examples above seem odd, see php.net/manual/en/… (String conversion to numbers).

Written by konforce

@konforce i see that. but the manual doesnt always give a clear picture. ive been using php for a long time. and ive never type casted

Written by Neal

I rolledback your last edit because I think you had valid questions. Also, I updated my question to answer these.

Written by Kevin Peno

@Kevin - ok. ddnt know if my last edit was relevant so i removed it.

Written by Neal

Perfectly relevant as it helps clearify your confusion :)

Written by Kevin Peno

Accepted Answer

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

Written by Kevin Peno
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki