0

Need a little help

I have

$_POST["zapremina"]=2000;
$_POST["starost"]="15%";
$_POST["namena"]="50%";

I want simple function to do this

$foo=(2000 - 15%) - 50%;

How to do that?

2
  • Is it $_POST["zapremina"]="2000"; $_POST["starost"]='15%'; $_POST["namena"]="50%"; ? Commented Mar 30, 2013 at 19:24
  • To convert a string into a integer, you just have to $a= (int) $b; Commented Mar 30, 2013 at 19:24

4 Answers 4

1

PHP is loosely typed, so you don't have to cast types explicity or do unnecessary operations (e.g. str_replace)

You can do the following:

$z = $_POST["zapremina"]; //$_POST["zapremina"]=2000;
$s = $_POST["starost"];   //$_POST["starost"]=15%;
$n = $_POST["namena"];    //$_POST["namena"]="50%;

$result = (($z - ($z *($s / 100))) - ($z * ($n / 100)));

Remember to use parentheses to have a readable code and meaningful var names.

Sign up to request clarification or add additional context in comments.

Comments

0

Like this:

$starostPercentage = (substr($POST["starost"], 0, -1) / 100);
$namenaPercentage = (substr($POST["namena"], 0, -1) / 100);

$foo = ($_POST["zapremina"] * (100 - $starostPercentage)) * $namenaPercentage;

This is what this does and why:

  • Convert the percentages (like 15%) from their text form to their decimal form (substr(15%) = 15, 15 / 100 = 0.15).
  • Calculate $foo with these decimals. 2000 - 15% is what you would write (as a human), but in PHP you need to write that as 2000 * (100 * 0.15), meaning: 85% of 2000).

1 Comment

You don't take $_POST["zapremina"] into account. Plus, it will result as : (2000 * 15) -50
0

I'd go with this:

  $zap = intval($_POST['zapremina']);
  $sta = intval($_POST['starost']);
  $nam = intval($_POST['namena']);
  $foo = ($zap * ((100-$sta)/100)) * ((100 - $nam)/100)

Comments

0

add this function and then call it

function calculation($a, $b, $c)
    {
        $b = substr($b, 0, -1) / 100;
        $c = substr($c, 0, -1) / 100;
        return (($a * $b) * $c);
    }

and now you can call

$foo = calculation($_POST["zapremina"], $_POST["starost"], $_POST["namena"]);

go with function most of times, because it will be helpful for reusability.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.