how to convert 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
eke21
Forum Newbie
Posts: 2
Joined: Fri May 01, 2009 11:43 am

how to convert string to int

Post by eke21 »

Hi, I have a php script that will get a line coming from a file. my problem is that, I have to compare the two values out of the lines. example :

line 1 --> I have 2,000 dollars.
line 4 --> my dollars = 1,000.00 only

i have to manipulate the values in the line, let's say 2000/1000 which is equal to 2.

how can i extract the numbers in the line and convert it to integer so that mathematical operations is possible?

thanks in advance!
user___
Forum Contributor
Posts: 297
Joined: Tue Dec 05, 2006 3:05 pm

Re: how to convert string to int

Post by user___ »

Use regular expressions. Converting is not a problem with Php(Like in Java/C++). Just make sure the extracted value is 0-9 and it is fine.

This is what I just made for you(It is just a start point). Assuming that cents are divided by ".":

Code: Select all

$string = "I have 2,000 dollars.";
$line   = "my dollars = 1,000.00 only";
$string =  round(preg_replace("/[^0-9\.]*/", "", $string), 2);
$line   =  round(preg_replace("/[^0-9\.]*/", "", $line), 2);
echo round($string/$line, 2);
Note: In Php 6, as far as I know it will not be the same, there will be strict data types.
hchsk
Forum Newbie
Posts: 2
Joined: Fri May 01, 2009 6:40 pm

Re: how to convert string to int

Post by hchsk »

a simpler method to convert to an integer value after extraction using regex is:

Code: Select all

intval($string);
eke21
Forum Newbie
Posts: 2
Joined: Fri May 01, 2009 11:43 am

Re: how to convert string to int

Post by eke21 »

wow! thanks a lot user___! it works perfectly!
I have some questions mate, what if i'm only interested in the value of 2 lines :
for example line 14&16?
coz thats the line where I want to perform the mathematical computation.

my code now gets all the lines in the file, and i am having problem finding out the lines of my interest.

Thanks man!
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: how to convert string to int

Post by McInfo »

1. Watch out for this scenario:

Code: Select all

$str = 'I have 3,000 in the safe and 20 in my wallet';
$num = preg_replace('/[^0-9\.]*/', '', $str); // 300020
2. If you want to make sure you have an integer, you can use type casting.

Code: Select all

$int = (int) $num;
PHP Manual: Type Casting

Some interesting things to be aware of with type casting:

Code: Select all

echo (int) '20000.00'; // 20000
echo (int) 'a20000.00'; // 0
echo (int) '20,000.00'; // 20
echo (int) '-20,000.00'; // -20
Edit: This post was recovered from search engine cache.
Post Reply