-1

I have an value in variable like below

$game = "4+9";

I want it to echo 13 , How to convert it to integer.

note : I get value of 4+9 from file_get_contents,

4 Answers4

3
echo array_sum(explode("+",$game));
D-Rock
  • 2,636
  • 1
  • 21
  • 26
  • with yours i get 7+3 = 0 ? – Vishnu Simbu Feb 26 '13 at 13:50
  • you must have something else going on. You say that you are getting 4+9 from file_get_contents... Is there more content coming in from the file into the $game variable? – D-Rock Feb 26 '13 at 13:56
  • its random addition between 2 numbers , if its 13 , i can echo "13"; – Vishnu Simbu Feb 26 '13 at 13:58
  • @VishnuSimbu `echo array_sum(explode('+','7+3'));` works for me - I quickly tested it on http://writecodeonline.com/php/ - you may need to check that `$game` is correctly set. – Fenton Feb 26 '13 at 13:59
0
$strings = explode("+", "4+9");
$value = intval($strings[0]) + intval($strings[1]);
echo $value
kbdjockey
  • 891
  • 6
  • 8
0

If you are just dealing with addition, you could split the string by the plus-operator and add the numbers.

$numbers = explode('+', $game);
$result = 0;
foreach($numbers as $num) {
    $result += intval($num);
}

This would get complex pretty quickly as you start adding other operators, brackets etc.

You could use eval to just run the text content of the file, but you have to be sure nobody will put anything nasty in the file.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Oh I answered the same, but any specific reason for using `intval` here? – Mr. Alien Feb 26 '13 at 13:47
  • I guess it is belt and braces really. `+=` in PHP is a mathematical operator, but quite a few languages I use infer whether `+=` is a mathematical or string operator based on types so I'm used to making the types explicit to avoid accidental concatenation ("49" in this case) - although in PHP that shouldn't happen. Also, if the string passed in was invalid, this would be more forgiving: `"4a+9b"`. This could be changed to `floatval` if non-integer numbers were anticipated. – Fenton Feb 26 '13 at 13:55
0

You should break your string into series of substrings with a loop. If you are 100% sure it's only "+" operator, then you can have simple code like this:

$data = explode('+', $game);

echo $data[0]+$data[1];

But what will happen if you have -, / or * ?

Also, you can always use eval() function, but this highly not recommended because of security issues.

Serge Kuharev
  • 1,052
  • 6
  • 16