PHP use string as operator - php

Say I have a string, $char. $char == "*".
I also have two variables, $a and $b, which equal "4" and "5" respectively.
How do I get the result of $a $char $b, ie 4 * 5 ?
Thanks :)

You can use eval() as suggested by #konforce, however the safest route would be something like:
$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){
case "*":
$result = $left * $right;
break;
case "+";
$result = $left + $right;
break;
// etc
}

safest method is a switch construct:
function my_operator($a, $b, $char) {
switch($char) {
case '=': return $a = $b;
case '*': return $a * $b;
case '+': return $a + $b;
etc...
}
}

The easiest but most dangerous method is to use eval.
$c = eval("return $a $char $b;");

take a look at the eval() function. you will need to build a proper php command and run inside the eval() to extract out the result.

You can do with eval however I would not suggest using eval.
If there is case operator can by anything you should check what operator is before using
switch($char)
{
case '*':
$result= $a * $b;
break;
case '+':
$result= $a + $b;
break;
}

<?php
$a = 'alex';
$b = "alex";
$c = "==";
function abc($a,$b,$c){
$d = 'return ($a '.$c.' $b) ? true : false;';
return eval($d);
}
if(abc($a,$b,$c)){
echo "condition true";
}else{
echo "condition false";
}
// echo $e;
?>

Related

Advanced php formatting need help understand layout

Here is the function:
function simplePresent($e) {
$w = ($f = preg_match)('/ey|se|d |[sI]$|We/', $a = $e[0]);
be == ($b = $e[1])
?
$b = $w ? $a == I ? am : are : is
:
$w ?: $b = $b == have ? has : $b .= $f('/[h-z]$/', $b) ? es : s;
return "$a $b $e[2]";
}
this is a solution on codefights. it handles formatting under defined parameters. I am trying to understand the function assignment to the variables $f and $w. Also the the use of variables with no quotes. lastly the nested question marks and colons. How is this functioning?
Thanks
The function preg_match() is being assigned to the variable $f and reused later in the code. $w is simply the result of preg_match(). For example:
<?php
$w = ($f = 'sprintf')("foo");
// same as this:
$f = 'sprintf';
$w = $f("foo");
// which is the same as this:
$w = sprintf('foo');
The unquoted values will first be interpreted as constants, and the undefined constants will be interpreted as strings. Here's how a proper constant definition looks:
<?php
define("foo", "bar");
echo foo;
echo bar;
// PHP Notice: Use of undefined constant bar - assumed 'bar'
// same as this:
echo "bar";
echo "bar";
The question marks and colons are part of a ternary statement. This is a useful shorthand, but PHP recommends against stacking them together as is done there (the result is "non-obvious.") A simple one looks like this:
<?php
echo ($foo == "foo" ? "equal" : "inequal");
$a = $b ? $c : $d;
// this is the same as:
if ($foo == "foo") {
echo "equal";
} else {
echo "inequal";
}
if ($b) {
$a = $c;
} else {
$a = $d;
}

PHP use result of as variable

Is it possible to use the result of an if with an OR statement as a variable for a function?
As example:
$a = true;
$b = false;
if ($a || $b) {
$this->functionCall($a)
}
Other example:
$a = false;
$b = true;
if ($a || $b) {
$this->functionCall($b)
}
Third and final exmaple:
$a = true;
$b = true;
if ($a || $b) {
$this->functionCall($a, $b)
}
So I need to detect what variable is true and pass it as a paramater. Is this even possible?
Any helps is appreciated!
Many thanks in advance
I'd do the logic bit inside a two-parameter function if I were you, as such :
function myFunc($a = false, $b = false) {
if ($a == true)
echo 'a';
if ($b == true)
echo 'b';
}
myFunc(); // echoes nothing
$a = true;
$b = false;
myFunc($a, $b); // echoes 'a'
$a = false;
$b = true;
myFunc($a, $b); // echoes 'b'
$a = true;
$b = true;
myFunc($a, $b); // echoes 'ab'
PHP 5.6+ version, filter out the falsely values (you can pass a callback to array_filter for different checks) and use those with the splat operator.
$params = array_filter([$a, $b]);
$this->callFunction(...$params);
No need for any IF checks and confusing in IF assignments.
Explore Variadic functions and Argument unpacking.

PHP: why my switch always picks the same value?

function getValue($v) {
$b = 22;
switch ($v) {
case ($v <= $b * 1.2):
$v1 = $b; break;
case ($v1 > $b * 1.2 && $v1 <= $b * 2.2):
$v1 = $b * 2; break;
case ($v1 > $b * 2.2 && $v1 <= $b * 3.2):
$v1 = $b * 3; break;
case ($v1 > $b * 3.2):
$v1 = $b * 4; break;
default:
$v1 = $b;
}
return $v1;
}
the getValue(25) or getValue(45) always returns 22.
I don't think you could use switch like that. It needs values. It does not accept boolean conditions. Check here http://php.net/manual/en/control-structures.switch.php
function getValue($v) {
$b = 22;
switch ($v) {
case ($v <= $b * 1.2):
$v1 = $b; break;
case ($v > $b * 1.2 && $v <= $b * 2.2):
$v1 = $b * 2; break;
case ($v > $b * 2.2 && $v <= $b * 3.2):
$v1 = $b * 3; break;
case ($v > $b * 3.2):
$v1 = $b * 4; break;
default:
$v1 = $b;
}
return $v1;
}
Your using $v1 instead of $v wrongly.
Above code will work.
You're checking the wrong variable, so you should replace $v1 with $v in the case statements throughout. But also, switch statements are designed to accept constant values, so you'd be better to replace them all with if.
In addition, parts of your expressions are redundant because you've already checked for them. After checking that $v <= $b * 1.2 and finding it isn't, there's no need to check that $v > $b * 1.2 in the next expression. Your default clause can never be matched because all values of $v are <= $b * 3.2 or > $b * 3.2.
function getValue($v) {
$b = 22;
if ($v <= $b * 1.2) {
return $b;
} elseif ($v <= $b * 2.2) {
return $b * 2;
} elseif ($v <= $b * 3.2) {
return $b * 3;
} else {
return $b * 4;
}
}
With a switch, you test the given value against the cases.
So your statement does $v == ($v <= $b * 1.2), $v == ($v1 > $b * 1.2 && $v1 <= $b * 2.2), etc.
You can do a switch and test against true:
function getValue($v) {
$b = 22;
switch (true) {
case ($v <= $b * 1.2):
$v1 = $b; break;
case ($v1 > $b * 1.2 && $v1 <= $b * 2.2):
$v1 = $b * 2; break;
case ($v1 > $b * 2.2 && $v1 <= $b * 3.2):
$v1 = $b * 3; break;
case ($v1 > $b * 3.2):
$v1 = $b * 4; break;
default:
$v1 = $b;
}
return $v1;
}
However in this case an if / else seems like the better choice:
function getValue($v) {
$b = 22;
if ($v <= $b * 1.2) {
$v1 = $b;
} elseif ($v1 > $b * 1.2 && $v1 <= $b * 2.2) {
$v1 = $b * 2;
} elseif ($v1 > $b * 2.2 && $v1 <= $b * 3.2) {
$v1 = $b * 3;
} elseif ($v1 > $b * 3.2) {
$v1 = $b * 4;
} else {
$v1 = $b;
}
return $v1;
}
Look at your case labels: they are the results of relational operations, so all of them evaluate to either true or false! %v will be compared to these Boolean values. That's why you're observing such similar output for your input cases.
Replace the switch with an if block and all will be well. And do review your use of $v1; did you mean that?
in your switch I can see variable $v1 in the second and third and fourth case so think of the condition which we don't go through the first case so what is the variable $v1 then ? it is not set yet so it goes to the case default or first case always.

php for nested loop and if not working

I'm new to php and I try to make a simple program. to show a result for ex : if the array only contains a the $result will be "a" , if b the $result will be "b", if a & b then "ab" etc. in this case the array contains a, b, and c and for some reason when I run it only shows "c".
here's my code :
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
for ($j=0; $j<sizeof($a); $j++) {
for ($k=0; $k<sizeof($a); $k++) {
for ($l=0; $l<sizeof($a); $l++) {
if ($a[$j] == "a"){
$result="a";
}
elseif ($a[$j] == "b") {
$result="b";
}
elseif ($a[$j] == "c") {
$result="c";
}
elseif ($a[$j] == "a" and $a[$k] == "b") {
$result="ab";
}
elseif ($a[$j] == "c" and $a[$k] == "b" and $a[$l] == "a") {
$result="abc";
}
elseif ($a[$j] == "b" and $a[$k] == "c") {
$result="bc";
}
}
}
}
echo ($result);
thanks in advance
Use only one loop and three flags. Try something like this
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
$hasA = false;
$hasB = false;
$hasC = false;
for ($j=0; $j<sizeof($a); $j++) {
if ($a[$j] == "a"){
$hasA = true;
}
elseif ($a[$j] == "b"){
$hasB = true;
}
elseif ($a[$j] == "c"){
$hasC = true;
}
}
if ($hasA) echo 'a';
if ($hasB) echo 'b';
if ($hasC) echo 'c';
First of all those loops aren't really necessary.
Use php switches.
switch($value){
case "a":
// Actions here
case "b":
// Actions here
}
What you are doing in those for loops is keep overriding $result with a new value.
In the end it shows the last letter it found.
Aside from the fact, what purpose this code has. Try to look for a php debugger I would recommend using Xdebug.
A debugger helps a programmer detect problems by stepping into the code line by line and showing the state of every variable.
A good tutorial and development environnement tutorial is found here
Let's take a different approach:
$array="asdasd";
$check=$arry[0];
$all_the_same=true;
for($i=1; $i<count($array); $i++){
if(array[$i] !== $check){
$all_the_same=false;
break;
}
}
What I've done is to check all letters in the array to see if they're all the same, and set $all_the_same to false if they're not. To find out if the array has the letter you want:
if($check==="a")
echo "has 'a'";
or perhaps the more civilized switch / case statement.
The problem with your code is that you run three loops over the same data. $j changes very slowly (every sizeof($a) squared to be precise) and it's the first thing you check so it's no surprise it always shows "c".
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
$result = '';
foreach($a as $value) {
if($value == 'a')
$result .= 'a';
if($value == 'b')
$result .= 'b';
if($value == 'c')
$result .= 'c';
}
echo $result;
Here is a smoother version of what you tried to do!
sort($array);
implode( array_unique( $array ) );
As #GarethL had mentioned
here is a simpler way to achieve this:
$a = array('a', 'b', 'c');
$result = '';
if(in_array('a', $a)){
$result .= 'a';
}
if(in_array('b', $a)){
$result .= 'b';
}
if(in_array('c', $a)){
$result .= 'c';
}
echo $result;
For the intention of the question, may meet this simple code
<?php
$a[0] = "b";
$a[1] = "a";
$a[2] = "c";
$result = implode($a);
echo $result;

concate php variable

When concatenate php variable result not showing.
$a = 5;
$b = 4;
$o = '+';
echo $a.$o.$b;
result showing 5+4; but i want show result 9
How can i do this, anybody can help me out.
Thanks in advance.
'+' is a string, so if you concate it with a number you get a string. You have to look into the value:
if ($o == '+') {
echo $a + $b;
}
Or what you probably want:
switch ($o) {
case "+":
echo $a + $b;
break;
case "-":
echo $a - $b;
break;
case "*":
echo $a * $b;
break;
case "/":
echo $a / $b;
break;
default:
echo 0;
}
Use the "eval()" function
As in:--
echo eval($a.$o.$b)
But be careful never "eval" anything that comes from a web page without validation.
You are concatenating with the string "+", so you get a string. You want to actually add the numbers:
$o = $a + $b;
echo $o;
concatenate joins strings. If you want normal arithmetic, just use a plus sign:
$a = 5;
$b = 4;
echo ($a + $b)
When you use concatenate PHP automatically set type of parameters STRING. You should write $c=$b+$a; echo $c;
You can do this:
function calc($a, $b, $o) {
$op = array('+', '-');
if (in_array($o, $op))
return eval('return '.(int)$a.$o.(int)$b.';');
return False;
}
$a = 5;
$b = 4;
$o = '+';
var_dump(calc($a, $b, $o));
But this is very ugly, you should rethink your logic.

Categories