p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: chapter 10


Message #1 by "fercam" <fercam@w...> on Sun, 9 Feb 2003 16:30:30 +0100
just a little question here: why is it needed to have (int) in the code? I
tried it and it worked without.

Message #2 by "cf" <fercam@w...> on Sun, 9 Feb 2003 15:47:59
woops, I forgot to say on page 329.
Message #3 by "Nikolai Devereaux" <yomama@u...> on Tue, 11 Feb 2003 10:31:37 -0800
> just a little question here: why is it needed to have
> (int) in the code? I tried it and it worked without.


I don't have the code in front of me, but I can guess:

If you retrieve a form data value, it's submitted as text.  If you want that
value to be treated as a different data type (in this case it's an integer),
then you have to convert it.


$var = (int) "5";  // assigns the integer 5 to $var,
                   // not the string "5".


This comes in useful especially when trying to sort an array.  Consider the
values 1, 4, 7, 10, 15, 210, 10052, and 60.

If these values are submitted to a page as strings and you try to sort them,
PHP will perform a character-based sort -- alphabetical, not numeric.  The
result would be: 1, 10, 10052, 15, 210, 4, 60, 7.  Clearly, this isn't
correct.

Even comparisons will fail:

if($mygrade > $yourgrade)
{
   echo "I'm smarter than you.";
}
else
{
   echo "You cheated.";
}


Now, what if $mygrade and $yourgrade were submitted via a form, and mygrade
was 9 and yourgrade was 86?  As strings, mygrade would be greater than
yourgrade.


Hope this helps,

nik


  Return to Index