Skip to content

Instantly share code, notes, and snippets.

@theshem
Last active December 15, 2015 12:39
Show Gist options
  • Save theshem/5262109 to your computer and use it in GitHub Desktop.
Save theshem/5262109 to your computer and use it in GitHub Desktop.
How to Calculate arithmetic operators in strings via PHP
<?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)
<?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)
<?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