Last active
December 15, 2015 12:39
-
-
Save theshem/5262109 to your computer and use it in GitHub Desktop.
How to Calculate arithmetic operators in strings via PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function calc($str) | |
{ | |
$compute = create_function('', 'return (' . trim($str) . ');' ); | |
return $compute(); | |
} | |
# Demonstration | |
$string = " (5 - 1) * (6 / 2 + 1) "; | |
$output = calc($string); | |
var_dump($output); // int(16) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# So we can merge two other tricks into this one, for more assurance | |
function calc($str) | |
{ | |
$compute = create_function('', 'return (' . trim($str) . ');' ); | |
return 0 + $compute(); | |
} | |
$string = " (5 - 1) * (6 / 2 + 1) "; | |
$output = calc($string); | |
var_dump($output); // int(16) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# How to convert a string number to Integer? | |
# This will do the trick ;) | |
function toInteger($str) | |
{ | |
return 0 + $str; | |
} | |
# Demonstration | |
$string = "-8"; | |
$output = toInteger($string); | |
var_dump($output); // int(-8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment