0

I try to solve this exercise, but Im not sure how to look for the solution. For my current knowledge my program should print out smg, but I get only error .

Error message :

     
Warning: Undefined variable $x in /in/NVFqg on line 6
Charile bit your finger!

Here is my code :

<?php 
function isBitten()
{

if ($x <= 50) { // line 6 //
   echo "Charile bit your finger!"; 
   $x = rand(0, 100);
}

else {
  echo "Charlie did not bite your finger";
}



  }

 ?>



<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Charlie</title>
  </head>
  <body>


     <?php
     isBitten();
      ?>

  </body>
</html>

Your help is much appreciated! Thank you!

  • 2
    Variables needs to be defined before you try and read from them. Here: `if ($x <= 50)`, you haven't defined `$x` yet but are trying to compare it, which is what throws the undefined variable error. – M. Eriksson Dec 27 '20 at 12:07

1 Answers1

1

Please move your random number statement ($x = rand(0, 100);) to the beginning of the function, as follows:

<?php 
function isBitten()
{
$x = rand(0, 100);

if ($x <= 50) { // line 6 //
   echo "Charile bit your finger!"; 
}

else {
  echo "Charlie did not bite your finger";
  }
}

 ?>

The reason: you have to generate the variable $x before the system can determine whether the variable $x is <=50

Ken Lee
  • 6,985
  • 3
  • 10
  • 29