Forum Moderators: coopster

Message Too Old, No Replies

string to int calculation

         

sifredi

10:48 pm on May 23, 2005 (gmt 0)

10+ Year Member



Here is what I have:

$string = "10/2";

How can I get the result from the calculation inside the string? I tried val() and int() with no luck.

Thanks

StupidScript

11:35 pm on May 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you will always be doing division between two integers, here's a working solution:

$string = "10/2";

$nums=explode("/",$string);

$result=($nums[0] / $nums[1]);

It's best to keep numbers and other elements separated, of course. The biggest headache for this type of conversion is that if you were to convert the string as-is to an integer, you'd lose everything from the "/" on.

How strict are you about the operator? Will it always be the same?

Timotheos

11:59 pm on May 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



eval('$string = 10/2;');
echo $string;

There must be a better way...

StupidScript

9:15 pm on May 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Particularly when the value of $string is unknown. i.e.

$string="10/2";

eval('$string2=$string;');

echo $string2;

Returns: 10/2

eval('$string2=10/2;');

echo $string2;

Returns: 5

But then ... so does:

$string2=10/2;

echo $string2;

So you couldn't use a variable for the evaluation without it remaining a string. Hmmm ...

Timotheos

9:37 pm on May 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Right, it depends on how you format the line of code. Makes more sense to lay it out like this...

$expression = "10/2";
$code = "\$string=$expression;";
eval($code);
echo $string;

I'm sure you'd want to evaluate the expression to make sure it only contains valid characters.

Tim

StupidScript

11:36 pm on May 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thank you, Tim. I surely would. :) That looks like a solution ... doesn't it?