I have a operator in a string .
$c['operator'] = ">=";
if($sub_total.$c['operator'].$c['value'])
{
echo $sub_total.$c['operator'].$c['value'];
}
it obtain output is 20610>=30000
I'd put the possible operators in a switch:
$result = null;
switch($c['operator'])
{
case '>=':
$result = $sub_total >= $c['value'];
break;
case '<=':
$result = $sub_total <= $c['value'];
break;
// etc etc
}
This is far safer than using eval, and has the extra benefit that it sanitises the input.
$sub_total.$c['operator'].$c['value'] is not a comparison but a string concatenation. A filled string is always true in PHP, hence the if-statement is always true.
String can't be interpreted as php code unless you use eval (be careful with it).
What you are doing in your example in if statement is that you concatenate strings and because string after concatenation is not null it's evaluated to true, so if statement is executed.
In your case solution would be to see which operator is used like #adam has written in his solution.
BTW, having logic in strings (and possibly outside of script) is not a good idea.
Use PHP eval to evaluate the code you constructed.
$c['operator'] = ">=";
if(eval($sub_total.$c['operator'].$c['value']))
{
echo $sub_total.$c['operator'].$c['value'];
}
You can't do that in PHP, you should do something like below :
if ($c['operator'] == '>=' and $sub_total >= $c['value']) {
// Do something
} else if ($c['operator'] == '<=' and $sub_total <= $c['value']) {
// Do something else
} // etc...
Take a look at the eval method. It's very dangerous though
http://php.net/manual/en/function.eval.php
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.
Apologies if this is basic, but I'm learning php.
What does this snippet of code actually do? I've seen it in the source code for a plugin but can't quite figure out what's going on
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
Thanks.
This is a short version of if...else. This is a Ternary Logic.
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
if $_POST['newName'] == "" is true then "Dude" and else $_POST['newName'].
and both the value will be set in $_POST['newName'].
You can write this like this: [Full form]
if($_POST['newName'] == "")
$_POST['newName'] = "Dude";
The ? is also known as the ternary operator. It is called the ternary operator because it takes three operands - a condition, a result for true, and a result for false. If that sounds like an if statement to you, you are right on the money - the ternary operator is a shorthand (albeit very hard to read) way of doing if statements. Here's an example:
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
?>
First there is a condition ($age < 16), then there is a question mark, and then a true result, a colon, and a false result. If $age is less than 16, $agestr will be set to 'child', otherwise it will be set to 'adult'. That one-liner ternary statement can be expressed in a normal if statement like this:
<?php
if ($age < 16) {
$agestr = 'child';
} else {
$agestr = 'adult';
}
?>
So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.
Sometimes while coding, you might feel that writing an if(...){...}else{...} might feel like overkill for small amounts of code:
$result;
if (20>3)
{
$result = "bigger!";
}
else
{
$result = "smaller!";
}
So for this reason, a short hand notation was created where you would be able to express the exact same statement but without the need for such a big structure:
$result = (20>3) ? "bigger!" : "smaller!" ;
Whatever is between = and ? would then be the condition that is normally between the ( and ) of if(...). If that expression then equates to true, the value obtained by $result would be: "bigger!", and if it equated to false, the result would be: "smaller!".
As Frayne said, it is the shortened version of conditional statement. When we write it in full form, it becomes this:
<?php
if($_POST['newName'] == "") {
$_POST['newName'] = "Dude";
} else {
$_POST['newName'] = $_POST['newName'];
}
Simple question really. I have come across an issue with work where it would be ideal to store >= <= and == into a variable to spit out into certain if statements wherever the case may be.
$numb1 = 5
$numb2 = 10
$option = >=
if($numb1 $option $numb2)
You can't put a var for testing this in a control instruction.
This will return some : syntax error, unexpected T_VARIABLE
You could use some eval() to do it, but it's not advisable.
Perhap's you could make something different with the following :
$option=$_GET['option']; // or POST or something else...
$numb1 = 5;
$numb2 = 10;
switch($option) {
case ">=":
if($numb1 >= $numb2){//someting}
break;
case "<=":
if($numb1 <= $numb2){//someting}
break;
case "==":
if($numb1 == $numb2){//someting}
break;
default://something else if there is no $option
break;
}
Or with a function like the following
function testVar($numb1,$numb2,$option)
{
// Same switch
}
Not without using eval() which is generally considered a bad idea
Doing it directly like that, will only work using eval() - Using eval is not considered good practice. The main problem being that if the eval() statements takes in user input the user can inject php into your code. That's obviously bad. Refer this thread - When is eval evil in php?
What you'd be better off doing is created a series of switch statements for all the various operations such as 'greater than', 'less than', 'equals' and so forth...
The best thing to do for this is to make a function call or object wrapper, and then call the function to achieve the same result.
Example:
$func = '__my_eq_op_';
if ($func($numb1,$numb2)) {
// Do stuff
}
The operator functions are then...
function __my_eq_op($a,$b) {
return $a == $b;
}
function __my_gte_op($a,$b) {
return $a >= $b;
}
function __my_lte_op($a,$b) {
return $a <= $b;
}
For example. So you can really just break it down into using the functions instead.
For this:
if ($x == $y)
The parser sees 6 tokens...
1) KEYWORD IF:
2) LPAREN
3) VAR X
4) EQ
5) VAR Y
6) RPAREN
The parser uses these tokens to construct the AST for the IF conditional. Your thinking needs to move away from seeing the "==" as a variable. It's an operator!
Is this possible?
$var_1 = 1;
$var_2 = 10;
$comparison = '>';
if($var_1 $comparison $var_2) {
// do something...
}
The syntax right now is not valid but is there a way to do this?
Not natively (except of course with eval). You will need to evaluate the various expressions yourself. Build a wrapper function and use a switch statement. Or for non-expression comparisons a simple map:
$var_1 = 1;
$var_2 = 10;
$comparison = '>';
$map = array(
">" => $var_1 > $var_2,
"<" => $var_1 < $var_2,
"==" => $var_1 == $var_2,
"!=" => $var_1 != $var_2,
);
if($map[$comparison]) {
// do something...
}
It is possible with
if (eval("{$var_1} {$comparison} {$var_2}")) {
But eval is strongly discouraged, so do this only if you can't achieve desired result otherwise
EDIT
As #mario noted, until PHP 5.3 this doesn't work. In 5.3 it does. So for older versions it should be
if (eval("return {$var_1} {$comparison} {$var_2};")) {
You probably should use eval(). As like in other programming languages, PHP’s eval() is also powerful and dangerous — be careful.
If you write something like the following code:
if (eval("$var_1 $comparison $var_2")) {
// ...
}
It won’t work. Because PHP’s eval() doesn’t evaluate an expression, but just execute a statement. So you should do like:
eval("\$condition = $var_1 $comparison $var_2;"); // semicolon required!
if ($condition) {
// ...
}
It would work well except $var_1 or $var_2 is not number. For example, if $var_1 is a string like 'hello', the code eval() executes becomes:
eval("\$condition = hello > 2;");
To avoid breaking this code, you should escape dollar signs of $var_1 and $var_2:
eval("\$condition = \$var_1 $comparison \$var_2;"); // don't escape $comparison's.
I'm not sure if this is possible without the hackish use of an eval statement. You could of course wrap simply test what comparison is being used within another if statement.
if($comparison == '>' && $var_1 > $var_2)
//Do something
elseif($comparison == '<' && $var_1 < $var_2)
//Do something, and so on
The eval method should work too if you build you code into an a string.
if(eval("$var_1 $comparison $var_2")) //Do something
But the first method is probably far more preferable.
You could also create a few functions like isGreaterThan($arg1, $arg2), isLessThan($arg1, $arg2), and then store the name of the function you want in the variable $comparison. Then you would use call_user_func_array() when you want to use it. Like so :
function isGreaterThan($val1, $val2) {
return $val1 > $val2;
}
/////////////
$var_1 = 1;
$var_2 = 10;
$comparison = "isGreaterThan";
if(call_user_func_array($comparison, array($var_1, var_2))) {
//do something
}
Sounds like you've got a few options. Hope this helps.
make the string a conditional, returning a value if true or false
short form if statement
$var_1 = 1;
$var_2 = 10;
$comparison = '>=';
eval("\$b=$var_1 $comparison $var_2?1:0;");
if ($b) {
//do something
}
I am trying to write would be a simple if condition.
function genderMatch($consumerid1, $consumerid2)
{
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1=$gender2)
echo 1;
return 1;
else
echo 0;
return 0;
}
The output of the getGender function is either a M or F. However, no matter what I do gender1 and gender2 are returned as the same. For example I get this output: MF1
I am currently at a loss, any suggestions?
if ($gender1 = $gender2)
assigns the value of $gender2 to $gender1 and proceeds if the result (i.e. the value of $gender2) evaluates to true (every non-empty string does). You want
if ($gender1 == $gender2)
By the way, the whole function could be written shorter, like this:
function genderMatch($cid1, $cid2) {
return getGender($cid1) == getGender($cid2);
}
You have to put two == for comparison. With only one, as you have right now, you are assigning the value to the first variable.
if($gender1=$gender2)
would become
if($gender1==$gender2)
this:
if($gender1=$gender2)
should be
if($gender1==$gender2)
notice the extra ='s sign. I think you might also need curly brackets for multiple lines of an if/else statement.
Your using the assignment operator = instead of comparsion operators == (equal) or === (identical).
Have a look at PHP operators.
You have some structural problems with your code as well as an assignment instead of a comparison.
Your code should look like this:
function genderMatch($consumerid1, $consumerid2){
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1==$gender2){
echo 1;
return 1;
}else{
echo 0;
return 0;
}
}
Notice the double '=' signs in the if statement. This is a comparison. A single '=' is an assignment. Also, if you want to execute more than 1 line of code with an if/else, you need brackets.
You are using a single = which sets the variable, ie. the value of $gender1 is set to be the value of $gender2.
Use the === operator instead: if($gender1 === $gender2). It is usually a good idea to do strict comparisons rather than loose comparisons.
Read more about operators here: php.net
Another alternative is to use strcmp($gender1, $gender2) == 0. Using a comparer method/function is more common in languages where the string-datatype isn´t treated as a primary data-type, eg. C, Java, C#.