How can I convert a string to int?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
theoretical_dreamer
Forum Newbie
Posts: 13
Joined: Mon May 22, 2006 12:53 am

How can I convert a string to int?

Post by theoretical_dreamer »

for example:

Code: Select all

<? 
$var1=12;
$var2="12"; //How can I convert this to int?

if ($var1==$var2)
{
 print "It works";
}
?>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: How can I convert a string to int?

Post by Christopher »

Code: Select all

<? 
$var1=12;
$var2=(int)"12"; //by casting to new type
$var2=intval("12"); //or using a conversion function

if ($var1==$var2)
{
 print "It works";
}
?>
(#10850)
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

For the record, the code in the first post works fine for me. PHP's loose typing means INT==STRING is fine .. it's only when you do INT===STRING it'd start to fail.
Post Reply