Jump to content

[SOLVED] Random Mathematical operators?


MasterACE14

Recommended Posts

I was wondering how(thats if it's possible) you can put a Mathematical Operator in a Variable. Let me try and show you what I am trying to explain.

 

 

The Following Example is what I am trying to do, except instead of using a set Mathematical Operator(The Plus sign in this case) I would like to have the 4 Main Mathematical Operators each in their own variable and have 1 randomly chosen to put in between the x and y variable in the result variable.

<?php
$x = 1;
$y = 1;
$result = ($x + $y);
echo("$result");

?>

 

Something along these lines, even though I know it doesn't work.

 

<?php

$plus = +;
$minus = -;
$divide = /;
$multiply = *;

rand(variable);

$x = 1;
$y = 1;
$result = ($x rand() $y);
echo("$result");

?>

 

Something Like that even though I know that, that is way off what it should be. please go easy on me, I'm just a noob  :D

 

Regards

 

MasterACE14

Link to comment
https://forums.phpfreaks.com/topic/52190-solved-random-mathematical-operators/
Share on other sites

Hi,

You can do simple thing as below...see if it is OK with you

<?php
function performOperation($operand1,$operand2,$operation){
$result = 0;
$output = "The result of $operand1 $operation $operand2 is:";
switch($operation){
	case '+':
		  $result = $operand1 + $operand2;
		  break;
	case '-':
		  $result = $operand1 - $operand2;
		  break;
	case '*':
		  $result = $operand1 * $operand2;
		  break;
	case '/':
		  if ( $operand2 != 0 ){
		  	$result = $operand1 / $operand2;
		  }else{
			echo 'Division by zero error';
		  }
		  break;
}
echo $output.$result;

}

$operations = array(1=>'+',2=>'-',3=>'*',4=>'/');

$index = rand(1,4);

$current_operation = $operations[$index];

$x = 2;
$y = 2;

performOperation($x,$y,$current_operation);

Thankyou Both of you.  ;D

 

I've Tried your script neel_basu, and I get:

 

Parse error: parse error, unexpected '=' in C:\WebServer\Abyss Web Server\htdocs\phpeval\index.php(52) : eval()'d code(2) : eval()'d code on line 1

 

"I run it through my PHP testing lab, makes life easier ^^ "

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.