0

I have a calculator function that displays the result when a user enters a query in a div (calcanswer) but often the query is not a calculation request, so the result is "query=" in which query represents the user input, and then nothing behind the = sign. I am wondering whether it is possible to implement a function that hides the div when this happens (i.e. there is no calculation).

PHP:

<?php
$a=$_GET['q'];
//$a="1/2";
$add = stripos($a, '+') !== false;
$sub = stripos($a, '-') !== false;
$mul = stripos($a, '*') !== false;
$div = stripos($a, '/') !== false;
if($add){
    $b=explode("+",$a);
    $n1=(float)$b[0];
    $n2=(float)$b[1];
    $n3=$n1+$n2;
}else if($sub){
    $b=explode("-",$a);
    $n1=(float)$b[0];
    $n2=(float)$b[1];
    $n3=$n1-$n2;
} else if($mul){
    $b=explode("*",$a);
    $n1=(float)$b[0];
    $n2=(float)$b[1];
    $n3=$n1*$n2;
} else if($div){
    $b=explode("/",$a);
    $n1=(float)$b[0];
    $n2=(float)$b[1];
    $n3=$n1/$n2;
}
?>

HTML:

<div class="calcanswer"><center>
  <h4 class="card-title pb-3 mbr-fonts-style display-7">
  <?= $a."=".$n3 ?>
</h4></center></div>
2
  • Hi there. I am right in saying that someone would put in the $_GET['q'] something along the lines of "1 + 2 ="? If so, what would you do or how are you limiting the user putting in "1 + 2 + 3 ="? I would allow the user to enter in two numbers and using a drop down list, to select the required operator (-+/*). That way, you don't have to worry about what is on the other side of "=". The question just needs a little bit more background information, then I can pen a function for you. Commented Apr 1, 2019 at 18:57
  • Hi sorry, it is in a search functionality I am working on, so it also shows other results next to it. Hope this clears things up. :) Commented Apr 1, 2019 at 19:00

2 Answers 2

1

I have been able to fix it by doing this:

<?php
        if(isset($n3)) {
        ?>

        <div class="calcanswer"><center>
          <h4 class="card-title pb-3 mbr-fonts-style display-7">
           <?= $a."=".$n3 ?>
        </h4></center></div>

        <?php } ?>

I want to thank @Tim Hinz for helping me in such a short amount of time & Jim Grant for taking time out of their day to help me.

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

Comments

0

Just do this:

<?php 
if(isset($_GET["query"])) {
?>

<div class="calcanswer"><center>
  <h4 class="card-title pb-3 mbr-fonts-style display-7">
   <?= $a."=".$n3 ?>
</h4></center></div>

<?php } ?>

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.