Re: PHP Newbie can't evaluate numerical string as number [message #175921 is a reply to message #175919] |
Mon, 07 November 2011 17:52 |
Denis McMahon
Messages: 634 Registered: September 2010
Karma:
|
Senior Member |
|
|
On Mon, 07 Nov 2011 16:25:42 +0000, Graham wrote:
> I'm a Perl veteran (well almost!) but a PHP newbie. I've got a simple
> subtraction formula in 'vars.php' as follows:
>
> <?php
> $formula = "!big_number - !small_number"; ?>
>
> I then include it in 'test.php' along with a few variables, do a bit of
> string replacement, run eval on it, then print it
>
> <?PHP
> include 'vars.php';
> $big_number = 30000;
> $small_number = 3000;
> $formula = str_replace("!", "$", $formula); eval("\$formula =
> \"$formula\";");
> //$formula = intval($formula);
> //settype($formula, "integer");
> print ("formula = $formula\n");
> ?>
>
> The above gives me...'formula = 30000 - 3000' when of course what I want
> is...'formula = 27000'
>
> A few of the many things I've tried are commented out. Please put me out
> of my misery someone!
Does the following working example help?
<?php
$big_number = 50000;
$small_number = 5000;
$formula1 = "\$result1 = \$big_number - \$small_number;";
$formula2 = "return(\$big_number - \$small_number);";
echo "\$formula1 = '{$formula1}'\n";
echo "\$formula2 = '{$formula2}'\n";
eval($formula1);
$result2 = eval($formula2);
echo "\$result1 = {$result1}\n";
echo "\$result2 = {$result2}\n";
?>
Rgds
Denis McMahon
|
|
|