Echoing out a usable operator in PHP [duplicate] - php

This question already has answers here:
Execute PHP code in a string [duplicate]
(3 answers)
Closed 8 years ago.
Say I had this code below:
$operator = "+";
$num1 = 10;
$num2 = 32;
echo "the sum of " . $num1 . " and " . $num2 . " is " . ($num1.$operator.$num2);
As you can see, I'm trying to use a variable to define the operator by concatenating it. However, when running this code, the operator is displayed as plain text instead of being used to answer the question.
Obviously, I get an output like this: "the sum of 10 and 32 is 10+32"
Surely I'm doing something wrong?

Avoid eval as much as possible. But here is the answer to do it with eval:
<?php
$operator = '+';
$num1 = 10;
$num2 = 32;
eval(sprintf('echo %d %s %d;', $num1, $operator, $num2));
Here a little cleaner code
$operator = '+';
$num1 = 10;
$num2 = 32;
switch ($operator) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
$result = $num1 / $num2;
break;
default:
echo "Invalid operator";
break;
}
echo 'Result: ' . $result;

Related

this function only adds numbers and I can not figure why?

this function only adds numbers and I can not figure why ?
function calculate($num1 , $num2 , $name = "+" )
{
switch ($name)
{
case "+" || "add" || "a";
return $num1 + $num2 ."<br>";
break;
case "-" || "subtract" || "s";
return $num1 - $num2 ."<br>";
break;
case "*" || "multiply" || "m";
return $num1 * $num2 ."<br>";
break;
default:
"";
}
}
I also tried if statement and didnt work.
Your syntax is not correct, do as follows:
switch ($name) {
case "+" :
case "add" :
case "a":
return $num1 + $num2 . "<br>";
case "-" :
case "subtract" :
case "s":
return $num1 - $num2 . "<br>";
case "*" :
case "multiply" :
case "m":
return $num1 * $num2 . "<br>";
default:
"";
}
By the way, you don't need to break if you return something.
More information :
Switch case multiple values
Switch Documentation

Arithmetic operations between variables

I'm beginner with php. I am trying to apply some random arithmetic operation between two variables
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
$result = $num1 . $operators[array_rand($operators)] . $num2;
echo $result;
it prints values like these
10+5
10-5
How can I edit my code in order to do this arithmetic operation?
While you could use eval() to do this, it relies on the variables being safe.
This is much, much safer:
function compute($num1, $operator, $num2) {
switch($operator) {
case "+": return $num1 + $num2;
case "-": return $num1 - $num2;
case "*": return $num1 * $num2;
case "/": return $num1 / $num2;
// you can define more operators here, and they don't
// have to keep to PHP syntax. For instance:
case "^": return pow($num1, $num2);
// and handle errors:
default: throw new UnexpectedValueException("Invalid operator");
}
}
Now you can call:
echo compute($num1, $operators[array_rand($operators)], $num2);
This should work for you!
You can use this function:
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = preg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
//As an example
echo calculate_string("10+5");
Output:
15
So in your case you can do this:
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
echo calculate_string($num1 . $operators[array_rand($operators)] . $num2);

php random operator and their operations

see my code below
$rand1 = rand(0,9);
$rand2 = rand(0,9);
$operator = array('*','/','+','-');
$randoperator = $operator[rand(0,3)];
$finaalvalue = $rand1."$randoperator".$rand2;
echo $rand1.$randoperator.$rand2.'='.$finaalvalue;
i want to take two random number and do random operation like +,-,*,/ and get their value
like 2-5=6
there is some problem while doing is what am i missing
The obvious answer is to use the eval function, but its use is highly discouraged:
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.
The other option is to write separate blocks of code that perform the desired operation, then choose the appropriate branch, for example, by using a switch...case statement:
<?php
$rand1 = rand(0, 9);
$rand2 = rand(0, 9);
$operator = array('*', '/', '+', '-');
$randoperator = $operator[rand(0, 3)];
switch ($randoperator) {
case "+":
$finaalvalue = $rand1 + $rand2;
break;
case "-":
$finaalvalue = $rand1 - $rand2;
break;
case "*":
$finaalvalue = $rand1 * $rand2;
break;
case "/":
$finaalvalue = $rand1 / $rand2;
break;
}
echo $rand1 . $randoperator . $rand2 . '=' . $finaalvalue;
if I'm reading your question right, you're computing a string, not applying the operator. You must apply code to rand1 and rand2 to compute the final value.
The easy way is to eval $finaalvalue ($finalvaalue = eval("return $finaalvalue ;");) before echoing it.
If you need the code to run fast, or don't trust the input, use a switch or a function map:
$operatorMap = array(
'+' => function($a, $b) { return $a + $b; },
'*' => function($a, $b) { return $a * $b; },
...
);
$finaalvalue = $operatorMap[$operator]($rand1, $rand2);
PHP anonymous functions run slow compared to methods and normal functions, so avoid them in tight loops where speed matters.
Is this a homework question? You should do your own work.
This should work for you:
(Also if you do random calculation's you would have to check that there is no division by zero)
<?php
function calculate_string( $mathString ) {
$mathString = trim($mathString);
$mathString = str_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
$rand1 = rand(0,9);
$rand2 = rand(0,9);
$operator = array('*','/','+','-');
$randoperator = $operator[rand(0,3)];
if($operator = "/" && $rand2 == 0)
echo "Division by zero!";
else {
$finaalvalue = calculate_string($rand1 . $randoperator . $rand2);
echo $rand1.$randoperator.$rand2.'='.$finaalvalue;
}
?>
Suggest you to calculate mathematics operation by switch case. Your system can't perform mathematics operation, it will generate a string. That is concatenation.
$rand1 = rand(0,9);
$rand2 = rand(0,9);
$operator = array('*','/','+','-');
$randoperator = $operator[rand(0,3)];
switch($randoperator){
case '+':
$finaalvalue = $rand1 + $rand2;
break;
case '-':
$finaalvalue = $rand1 - $rand2;
break;
case '/':
if(!$rand2) $rand2++;
$finaalvalue = $rand1 / $rand2;
break;
case '*':
$finaalvalue = $rand1 * $rand2;
break;
}
echo $rand1.$randoperator.$rand2.'='.$finaalvalue;

Operators (operands?) as Parameters

I am trying to avoid duplicating my code by checking the variable if it is a certain operator.
Basically..
$op = $_POST['operator'];
$x = 5;
$y = 2;
$result = $x /* $op instead of '+'/'-'/'*'/'/'/'%' */ $y;
Is this possible or will I have to send the operator as a String and duplicate the code per operator type?
It's a lot safer to do something like this:
$x = 5;
$y = 2;
switch($_POST['operator']){
case '+':
$result = $x + $y;
break;
case '-':
$result = $x - $y;
break;
case '*':
$result = $x*$y;
break;
case '/':
$result = $x/$y;
break;
case '%':
$result = $x % $y;
break;
default:
$result = 'Operator not supported';
}
Something along those lines.
Ahem. You can eval.
$result = eval("$x $op $y");
But this is DANGEROUS and you should sanitize your variables with great care. There is a saying that goes something like "If your problem requires use of eval, then the problem is wrong." Something like that. It's almost certainly preferable to do something like this:
function apply_op($x, $y, $op) {
switch ($op) {
case '+': return $x + $y;
...
}
}
you can make this:
$operators = array("+", "-","*","%","/");
$op = $_POST["operator"];
if(in_array($op, $operators)) {
echo eval("$x $op $y");
} else {
echo "Operator not supported";
}

Convert Money to Text in PHP [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I need to convert say $89.50 to Eighty-Nine Dollars and Fifty Cents using PHP. Is there a function I'm missing somewhere?
Here's a start for you. It's a recursive function I wrote a while back (part of solving a Project Euler problem 17) that converts numbers to letters... It can handle some pretty big numbers ;)
All you need to do is add the dollars and cents components and modify according to need. So basically you'd have to call the function once for the dollar amount and once for the cents component. I don't think there's a native PHP funciton for this. You'd have to use a library (like Pear) function.
(You can see the function in action):
<?php
function translateToWords($number)
{
/*****
* A recursive function to turn digits into words
* Numbers must be integers from -999,999,999,999 to 999,999,999,999 inclussive.
*
* (C) 2010 Peter Ajtai
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See the GNU General Public License: <http://www.gnu.org/licenses/>.
*
*/
// zero is a special case, it cause problems even with typecasting if we don't deal with it here
$max_size = pow(10,18);
if (!$number) return "zero";
if (is_int($number) && $number < abs($max_size))
{
switch ($number)
{
// set up some rules for converting digits to words
case $number < 0:
$prefix = "negative";
$suffix = translateToWords(-1*$number);
$string = $prefix . " " . $suffix;
break;
case 1:
$string = "one";
break;
case 2:
$string = "two";
break;
case 3:
$string = "three";
break;
case 4:
$string = "four";
break;
case 5:
$string = "five";
break;
case 6:
$string = "six";
break;
case 7:
$string = "seven";
break;
case 8:
$string = "eight";
break;
case 9:
$string = "nine";
break;
case 10:
$string = "ten";
break;
case 11:
$string = "eleven";
break;
case 12:
$string = "twelve";
break;
case 13:
$string = "thirteen";
break;
// fourteen handled later
case 15:
$string = "fifteen";
break;
case $number < 20:
$string = translateToWords($number%10);
// eighteen only has one "t"
if ($number == 18)
{
$suffix = "een";
} else
{
$suffix = "teen";
}
$string .= $suffix;
break;
case 20:
$string = "twenty";
break;
case 30:
$string = "thirty";
break;
case 40:
$string = "forty";
break;
case 50:
$string = "fifty";
break;
case 60:
$string = "sixty";
break;
case 70:
$string = "seventy";
break;
case 80:
$string = "eighty";
break;
case 90:
$string = "ninety";
break;
case $number < 100:
$prefix = translateToWords($number-$number%10);
$suffix = translateToWords($number%10);
$string = $prefix . "-" . $suffix;
break;
// handles all number 100 to 999
case $number < pow(10,3):
// floor return a float not an integer
$prefix = translateToWords(intval(floor($number/pow(10,2)))) . " hundred";
if ($number%pow(10,2)) $suffix = " and " . translateToWords($number%pow(10,2));
$string = $prefix . $suffix;
break;
case $number < pow(10,6):
// floor return a float not an integer
$prefix = translateToWords(intval(floor($number/pow(10,3)))) . " thousand";
if ($number%pow(10,3)) $suffix = translateToWords($number%pow(10,3));
$string = $prefix . " " . $suffix;
break;
case $number < pow(10,9):
// floor return a float not an integer
$prefix = translateToWords(intval(floor($number/pow(10,6)))) . " million";
if ($number%pow(10,6)) $suffix = translateToWords($number%pow(10,6));
$string = $prefix . " " . $suffix;
break;
case $number < pow(10,12):
// floor return a float not an integer
$prefix = translateToWords(intval(floor($number/pow(10,9)))) . " billion";
if ($number%pow(10,9)) $suffix = translateToWords($number%pow(10,9));
$string = $prefix . " " . $suffix;
break;
case $number < pow(10,15):
// floor return a float not an integer
$prefix = translateToWords(intval(floor($number/pow(10,12)))) . " trillion";
if ($number%pow(10,12)) $suffix = translateToWords($number%pow(10,12));
$string = $prefix . " " . $suffix;
break;
// Be careful not to pass default formatted numbers in the quadrillions+ into this function
// Default formatting is float and causes errors
case $number < pow(10,18):
// floor return a float not an integer
$prefix = translateToWords(intval(floor($number/pow(10,15)))) . " quadrillion";
if ($number%pow(10,15)) $suffix = translateToWords($number%pow(10,15));
$string = $prefix . " " . $suffix;
break;
}
} else
{
echo "ERROR with - $number<br/> Number must be an integer between -" . number_format($max_size, 0, ".", ",") . " and " . number_format($max_size, 0, ".", ",") . " exclussive.";
}
return $string;
}
?>
http://pear.php.net/package-info.php?package=Numbers_Words
Because clearly "no" wasn't the right answer to this question.
ยป Summary
The PEAR Numbers_Words
package provides methods for spelling
numerals in words.
No, I believe you need to write one yourself. It's quite straightforward to implement but there are a bunch of corner cases you'll need to handle.
No, there is no such function in PHP. The easiest is if you download some code from the internet.

Categories