Grow your CSS skills. Land your dream job.

Fatal error: Unsupported operand types *(issues with basic math)*

  • # February 20, 2014 at 1:15 am
    <?php
    // Attila Hajzer
    $weight = $_POST["txtWeight"];
    $height = $_POST["txtHeight"];
    $unit = $_POST["optUnit"];
    $message = "";
    
    if($unit == "metric")
    {
        $bmiCalc = $weight/($height*$height); #This Line
        $message = "Metric BMI: $bmiCalc";
    }
    else
    {
        $bmiCalc = ($weight * 703)/($height * $height);
        $message = "Imperial BMI: $bmiCalc";
    }
    
    ?>
    

    What am I doing wrong ?

    # February 20, 2014 at 10:40 am

    Have you tried casting to int?

    It’s possible you’re trying to multiply strings or something. I think, if it’s only that one line causing a problem, when you multiply it in the other equation PHP will automatically cast it as an int because that’s what it thinks you want? Not sure…

    http://www.php.net/manual/en/language.types.type-juggling.php

    # February 20, 2014 at 1:32 pm

    Your code worked on my local machine with some sample data… I tried replicating the data as if everything was a string and it worked. But I suggest you type juggle and deal with appropriate data types.

    This worked for me as well:

    // $weight = (float) $_POST["txtWeight"];
    // $height = (float) $_POST["txtHeight"];
    // $unit = (string) $_POST["optUnit"];
    // Our Sample Data
    $weight = (float) '185.33';
    $height = (float) '5.11';
    $unit = (string) ' ';
    $message = ' ';
    
    switch ($unit) {
      case 'metric':
       $bmiCalc = $weight/($height*$height);
       echo $message = 'Metric BMI: ' . $bmiCalc;
      break;
    
      default:
        $bmiCalc = ($weight * 703)/($height * $height);
        echo $message = 'Imperial BMI: ' . $bmiCalc;
      break;
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".