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
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);

Link to comment
Share on other sites

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 ^^ "

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.