0

When I first load the code (I don't input anything), the output will be like this. How do I hide the notice or maybe fix the undefined index? notice : undefined index always showing up when the first load

enter image description here

<h5 id="result" name="result" class="font-weight-bold mt-4">
    <?php  
        $numberTarget = $_GET['no'];
        $anArray = array(100, 44, 2, 80, 5, 13, 11, 4, 120);
        

        function linearSearch($anArray, $element) {
            for ($i = 0; $i < sizeof($anArray); $i++) {
                    if ($anArray[$i] == $element) {
                        return $i;
                    }   
                }  
                    return -1;
        };

        $output = linearSearch($anArray, $numberTarget);

        if($output != -1) {
            echo $numberTarget, " found at index ", $output;
        }
        else if ($output = -1) {
            echo "not found";
        }

    ?>  
</h5>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46

1 Answers1

0

As per the comment isset( $_GET['no'] ) ) allows you to fork the logic based upon the existence of a variable - this should prevent that particular issue

<h5 id="result" name="result" class="font-weight-bold mt-4">
    <?php 

        if( isset( $_GET['no'] ) ){# test that the querystring contains the vaiables of interest before using them
            $numberTarget = $_GET['no'];
            $anArray = array(100, 44, 2, 80, 5, 13, 11, 4, 120);
            

            function linearSearch($anArray, $element) {
                for ($i = 0; $i < sizeof($anArray); $i++) {
                        if ($anArray[$i] == $element) {
                            return $i;
                        }   
                    }  
                        return -1;
            };

            $output = linearSearch($anArray, $numberTarget);

            if($output != -1) {
                echo $numberTarget, " found at index ", $output;
            } else if ($output = -1) {
                echo "not found";
            }
        }
    ?>  
</h5>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46