How can I use x symbol as a multiplication instead of * in php array?

this is where I am declaring array of operators for generating an expressions

   // Read operations from the POST params and map the array that looks like fo my purpose
//    ['Addition', 'Multiplication'] as  ['+', '*']
$operations_map = array(
    'Addition'       => '+',
    'Subtraction'    => '-',
    'Multiplication' => '*',
    'Division'       => '/',
);
$operations = array_map(function($operation_name) use ($operations_map){
    return $operations_map[$operation_name];
}, $_POST['operation'] ?? []);  



 // generate expressions using the specified random seed
srand($seed);
$expressions = array();
for ($i = 1; $i <= $num_questions; $i++) {
    $expression = generate_expression($num_operands, $operations, $num_digits);
    $expression_string = implode(" ", $expression);
    $result = eval("return ($expression_string);");
    $expressions[] = compact("expression", "result");
}

return compact(
    'play',
    'seed',
    'num_digits',
    'num_questions',
    'num_operands',
    'operations',
    'expressions',
    'duration'
);

}

here I wanat to display x as a multiplication sign and perform the operation instead of using * sign , I have tried many ways like replacing it directly with x , by using &times also but eval function is showing error every time I am rrequesting output through my form
The rest of the code is working perfectly but with * symbol ,

what should I do ?

x is not a legitimate algebra sign in computers. In almost all languages, * is the sign for multiplication. Using x in PHP will make PHP assume that you are trying to reference a constant. x is a letter and not an operator. Also, eval is a dangerous function. You should use it with caution.

http://php.net/manual/en/function.eval.php

You’d have to translate your operator before you pass it in to the eval() function, that way you can display what you want and have it not matter.

3 Likes

@droopsnoot Is this correct way to translate it and if it is then hoq can I translate it i. e with some variable or any thing like that ?

               Multiplication' => ['op' => '*', 'display' => 'x']

I would just modify your display routine to look at each operand it displays, and if it’s “*”, echo “x” instead, otherwise echo the operand.

2 Likes

hey thanks its working now

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.