NYCPHP Meetup

NYPHP.org

[nycphp-talk] Eval question

Tim Lieberman tim_lists at o2group.com
Thu Oct 12 14:32:36 EDT 2006


You have an echo problem, not an eval problem.

$x = 2;
$y = 3;

echo "Basic string interpolation: ";
echo "$x * $y";
echo "<br/>evaluate and echo results: ";
echo $x * $y;
echo "<br/>See?";

Since the echo statement you're eval'ing has a single argument, a
double-quoted string, PHP does the string interpolation.  string
interpolation does not evaluate expressions in the string, it simply
converts variable names to the data they contain.

If you pass an expression to echo, however, PHP will evaluate the
expression, and output the result as a string.

HTH

-Tim



LK wrote:

> The reason I don't want to use regexp is because eventually I want to
> have an arbitrary formula for $calc_str, and I don't want to design my
> own evaluation compiler with regexp - that's what eval() is supposed
> to do, or so it seems.
>
> ----- Original Message ----
> From: Chris Merlo <chris at theyellowbox.com>
> To: NYPHP Talk <talk at lists.nyphp.org>
> Sent: Thursday, October 12, 2006 10:26:43 AM
> Subject: Re: [nycphp-talk] Eval question
>
> On 10/12/06, *LK* <lk613m at yahoo.com <mailto:lk613m at yahoo.com>> wrote:
>
>     <?php
>       $x = 3;
>       $y = 4;
>       $calc_str = '$x * $y';
>       eval("echo \"$calc_str\";");
>     ?>
>
>     I want to evaluate the expression $x * $y (x times y). But when I
>     run it thru the eval() function it returns "3 * 4" instead of
>     "12". It seems to interpret * as a string instead of a
>     multiplication operator. Any suggestions greatly appreciated 
>
>
> I haven't had my coffee yet, but I would guess that it has something
> to do with those single quotes.
>
> But there's a bigger question here:  Why do you want to store the
> expression in a string?  Just store the $x and the $y, and multiply
> them when you have to.  If there's some larger issue at hand, like you
> have to read the expressions from a file or something, use the regexp
> functions to get the two operands and the operator, and then do the
> math you have to do.
> -c
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com <http://www.nyphpcon.com/>
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
>
>
>------------------------------------------------------------------------
>
>_______________________________________________
>New York PHP Community Talk Mailing List
>http://lists.nyphp.org/mailman/listinfo/talk
>
>NYPHPCon 2006 Presentations Online
>http://www.nyphpcon.com
>
>Show Your Participation in New York PHP
>http://www.nyphp.org/show_participation.php
>  
>




More information about the talk mailing list