I have tried many different combinations of code using the eval command. However my answer is always blank. Here is a simple one i tried.
$equation = "18 - (18 * 2) - 1";
$var = eval($equation);
echo "answer: " . $var;
I understand this does not need the eval code, but the real code I am working on does. It just always shows up blank.
Solution
Add return inside the evaluated statement, otherwise the eval() won't know what to return:
$equation = '2 + 2 * 2';
$var = eval("return $equation;");
Proof, that the above works: http://ideone.com/bTtIH
About superiority of return vs. setting variable
More from the documentation of eval():
eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned.
In other words: there is no need to pollute the namespace, you can get what you want directly from what eval() returns.
You need to set the variable in the equation when you pass it to eval() to make it a valid and complete PHP expression:
$equation = "18 - (18 * 2) - 1";
eval( '$var = ' . $equation . ';');
echo "answer: " . $var;
Or, you can return the value:
$var = eval( 'return ' . $equation . ';');
Now you can do echo $var;, as seen in this demo.
That being said, eval() use is usually discouraged, as the underlying problem is typically solved with other means.
Related
If I have:
$compare = "5<6";
How do I look at the compare variable and return the value true. The input needs to be a string so taking away the " won't help. The string could be very complex so I'm looking for a function already in PHP which can run this, or something that someone has written before which can do this. I've tried the eval() function but that doesn't work, so:
$compare = "5<6";
echo eval($compare);
just errors. Thanks for your help in advance.
Using code evaluation functions are something that should be discouraged, because it may lead to a lot of security problems, but if you want to keep your logic that way, you must evaluate a valid code:
<?php
$compare = "5 > 6";
eval("\$result = $compare;");
var_dump($result);
Your comparing stringmust be used inside the eval function like it would be done in the normal code, not expecting a return value. So what I changed in this sample code is that I used a variable named $result to store the value from the evaluated code.
As you will see when running this code, the $result will be a boolean value (false in this sample, because 5 is not greater than 6, obviously).
Try this:
<?php
$compare = "5<6";
eval('$output = '.$compare.';');
echo $output;
?>
From PHP documentation: http://php.net/manual/en/function.eval.php
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged.
If you have carefully verified that there is no other option than to
use this construct, pay special attention not to pass any user
provided data into it without properly validating it beforehand.
You can display with echo directly:
<?php
$compare = '5<6';
echo $compare. "\n";
echo eval("return $compare;");
?>
Or You can store result in variable to display later:
<?php
$compare = '5<6';
echo $compare. "\n";
$result = eval("return $compare;");
echo $result;
?>
Be careful ;)
If you wanted to avoid eval it's easy enough to parse comparison expressions. Just split the string on a comparison operator and return the result of the corresponding comparison.
function compare($expr) {
$expr = preg_split('/(>=|<=|<|>|=)/', $expr, -1, PREG_SPLIT_DELIM_CAPTURE);
list($lhs, $op, $rhs) = $expr;
switch ($op) {
case '<': return $lhs < $rhs;
case '<=': return $lhs <= $rhs;
case '>': return $lhs > $rhs;
case '>=': return $lhs >= $rhs;
case '==': return $lhs == $rhs;
}
}
Apparently I missed the bit about "the string could be very complex" when I read the question initially, so this may not be helpful in your case, but I'll leave it here for future reference.
This question already has answers here:
PHP is confused when adding and concatenating
(3 answers)
Closed 6 years ago.
Today i am working on a small PHP code to plus/minus and multiply, but i end up found something which i wasn't knew before.
I was Plus 2 value, 123456+123456=24690 and my code is this:
<?php
$value1=12345;
$value2=12345;
$output=$value1+$value2;
echo $output;
?>
Which return a correct value:
So than i have to print this value with string Like this:
Total Value: 24690
I use this code:
echo 'Total Value:'.$value1+$value2;
Its return: 12345 instead of
Total Value: 24690
I know that "." isn't a Arithmetic operators, so i need small explanation why is this doing that.
But when i do
echo 'Total Value:'.($value1+$value2);
Its work fine!
Little Confused!
It first concatenates the $value1 with the string and then tries to add it to a string and number can't be added to string and hence you get that output.
While using braces, it just concatenates the contents of the brace and performs the mathematical operation inside the brace.
It follows BODMAS
When you
echo 'Total Value:'.$value1+$value2;
code execution will be like this actually:
echo ('Total Value: ' . $value1) + $value2;
This behavior is called Type Juggling. From the manual it states:
a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.
Example:
$foo = "1"; // $foo is string (ASCII 49)
$foo *= 2; // $foo is now an integer (2)
More examples on the link.
$gted = (object)'>';
if(200 $gted 300){
echo 'wow it worked';
}else{
echo 'no it didnt work';
}
I am trying to convert the '>' to a conditional > to use in an if statement. Thanks.
This will not work the way that you have it. Variables cannot be be interpreted as operators in PHP directly, see also this question.
Even if you could interpret a variable as an operator, what you have in your string 'object' is not a greater-than sign, it is an HTML entity that, when interpreted as an HTML entity, yields something that looks like a greater-than sign.
This question has some answers that include some workarounds for arithmetic operators which can be used to store results to be evaluated inside of an if statement. As an example for use in this answer, I borrowed and slightly modified part of this answer by #user187291 that uses create_function:
$operator = '+';
$func = create_function('$a,$b', "return \$a $operator \$b;");
$result = $func(5, 1);
echo $result;
The echo'd result would be 6, as you would expect. You could change what operator is being used so that the pseudo-anonymous function instead returns a boolean value which you could then plug into an if statement:
$operator = '>';
$func = create_function('$a,$b', "return \$a $operator \$b;");
$result = $func(200, 300);
if($result) {
echo 'wow it worked';
} else {
echo 'no it didnt work';
}
Except in extreme and very specific circumstances that I cannot currently imagine, I would not think this to be a good idea.
Don't think this exists but just want to make sure.
Is there a reverse for the .= operator in php.
example:
[$x .= $y] === [$x = $x.$y]
looking for:
[$x ? $y] === [$x = $y.$x]
No, there isn't.
The PHP manual documentation only lists two operators:
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
When you want to prepend to a string, just do $str = $add . $str. There is no need for a "special operator" here. If you use it frequently and don't want to retype it every time, you can create a function like this:
function prepend($text, $add) {
return $add . $text;
}
But, as you can probably guess, it's pointess.
Amal Murali's answer gave me an idea.
function p(&$x,$y){
$x = $y.$x;
return $x;
}
Now instead of having to type out;
$var1 = $var2 . $var1;
You can just do:
p($var1, $var2);
If you send the first variable as reference it does clean the code a bit.
Variables:
$var = ' world';
$var2 = 'Hello';
Usage
echo p($var, $var2);
or
p($var, $var2);
echo $var;
is now equal to:
$var = $var2 . $var1;
echo $var;
I have a variable that is...
$whatever = "5865/100";
This is a text variable.
I want it to calculate 5865/100 , so that I can add it to other numbers and do a calculation.
Number_format doesn't work, as it just returns "5,865". Whereas I want it to return 58.65
I could do...
$explode=explode("/",$whatever);
if(count($explode)=="2") {
$whatever = $explode[0]/$explode[1];
}
But it seems rather messy. Is there a simpler way?
Evaluate as PHP expression, but first check if it contains only digits and operators and space, and suppress any errors.
if (preg_match('/^[\d\+\-\/\*\s]+$/', $s)) {
#eval('$result = ' . $s . ';');
}
You can use the eval function to evaluate a string as code. However, you have to be careful as to where this code comes from because it will execute anything passed to it, not just simple math. If you knew your string contained a mathematical formula, you could do the following
$answer = 0;
$whatever = "5865/100";
eval ('$answer = ' . $whatever . ';');
print($answer);