How to fix the notice that always showing up when I load the page for the first time?

Viewed 33

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 when first load][1]

<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>
1 Answers

Check to make sure the target is actually set. Put this:

if(!isset($_GET['no'])) { exit; }

right before the first line in your php block:

$numberTarget = $_GET['no'];

That way, if $_GET['no'] is empty, the code will terminate without trying to run.

Related