1

I am trying to write a simple script to act as a sort-of captcha in a form. I know this isn't nowhere near as good as using a captcha but I wanted to do it as I'm new to PHP and it's good learning.

<?php $a = rand(1, 10); $b = rand(1, 10); $array = array( "+", "-", "/", "*" ); $operator = $array[array_rand($array)]; $answer = ; ?> 

What should I use to calculate $answer?

I need PHP to do $answer = $a $operator $b, for example $answer = 8 + 2 so $answer = 10.

11
  • eval() does the trick, however do your research first, because if done wrong, using eval can be dangerous. Commented Apr 21, 2015 at 12:49
  • Smells like homework ... well, why not. $answer = eval($a . $operator . $b). Yes, i do know eval is evil, that's what everyone says, but in that case, it's completely fine. Commented Apr 21, 2015 at 12:49
  • I would go for the approach with the switch statement for your requirements. (I wouldn't use evil()) in the dupe. Commented Apr 21, 2015 at 12:49
  • 1
    This might Works $answer = $a +$operator +$b; echo $answer; Commented Apr 21, 2015 at 13:02
  • 1
    @Enigma Indeed, it does, that's probably the best solution I've seen so far, nice! Commented Apr 21, 2015 at 13:08

0