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,
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,
echo array_sum(explode("+",$game));
$strings = explode("+", "4+9");
$value = intval($strings[0]) + intval($strings[1]);
echo $value
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.
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.