# Computer Guess Num Game | Computer Guesses Your Number

## Recommended Posts

I have been working on a PHP guess number game. The version where the person has to guess is finished and works fine, the code is below. What I need to do is convert the code so that the computer guesses the number. I know the basic concept that i need to go about it but need help coding it from the other perspective. If anybody has suggestions of how to go about it that would be much appreciated.

```<?php
\$guess=\$_POST["guess"];
\$counter=\$_POST["counter"];
\$number=\$_POST["number"];
if(empty(\$number)){
echo "<h4>Welcome! I have a number between 1 and 100. Please guess it.<h4>\n";
\$number=rand(1,100);
\$counter=0;
} else {
if(\$number==\$guess){
\$counter++;
echo "<h4>Well done! You guessed \$number in \$counter steps.<h4>\n";
}
if(\$guess<\$number){
\$counter++;
echo "<h4>Too low. Guess a higher number<h4>\n";
}
if(\$guess>\$number){
\$counter++;
echo "<h4>Too high. Guess a lower number<h4>\n";
}
}
echo <<<HERE
<form method="post" action="guessNum.php">
<input type = "hidden"
name = "number"
value = "\$number">
<input type = "hidden"
name = "counter"
value = "\$counter">
<input type = "text"
name = "guess"
value = "">
<input type="submit"
value="Guess">
</form>
HERE;
?>
```

##### Share on other sites

If I understand you correctly I'll give it a try.

```<?php
// Get the number the user entered
\$number = \$_POST['number'];

// Get the computer guess
\$guess = rand(1,100);

if(\$guess != \$number) {
echo "The computer guessed wrong!";
} else {
echo "The computer guessed right!";
}
?>
```

The code you have now seems like it would fit right in so, just needs a little updating. You might run into some problems with the hidden fields that you're using. I suggest using a \$_SESSION variable instead or the user can javascript inject anything they want into the field. When the user is done with the game, unset the variable

Edited by SocialCloud
##### Share on other sites

If I understand you correctly I'll give it a try.

```<?php
// Get the number the user entered
\$number = \$_POST['number'];

// Get the computer guess
\$guess = rand(1,100);

if(\$guess != \$number) {
echo "The computer guessed wrong!";
} else {
echo "The computer guessed right!";
}
?>
```

The code you have now seems like it would fit right in so, just needs a little updating. You might run into some problems with the hidden fields that you're using. I suggest using a \$_SESSION variable instead or the user can javascript inject anything they want into the field. When the user is done with the game, unset the variable

well yeah that is a simple method to do it, but I want to make sure that the computer does it in the most efficient way as possible. So something to the effect of they guess 50 initially then if it's high or low they go 50% +/- the previous guess. so if it were too low then they would guess 75, if that's too low then they would guess half way between 75 and 100, and continue on. The previous guess if it's not right becomes the new lower or higher bound. Does that make more sense, and how would the hidden fields cause some issues with that?

##### Share on other sites

This will make it sort of messy (at least what I will give as an example) and hopefully you can find a way to convert it to your liking

```<?php
// Get the number the user entered
\$number = \$_POST['number'];

// Get the computer guess
\$guess = rand(1,100);

if(\$guess != \$number) {

echo "The computer guessed wrong!";

// start intervals here
if(\$counter == 1) {

if(\$number < 50) {
\$new_guess = rand(0,49);
} else if(\$number >= 50) {
\$new_guess = rand(50,100);
}

} elseif(\$counter == 2) {
// you can continue to do methods like this until it's impossible to get it wrong.

}

} else {
echo "The computer guessed right!";
}
?>
```

I would highly suggest setting \$_SESSION variables as yes this may cause an issue. The only ones I would give variables to is the computers random number and the counter. If a user were to view the source of the page they would see and could edit what their counter is, as well as the computer's number.

And in this method of the computer guessing I'm assuming you would need to have a continue or cancel button for the user to click, which I would set a \$_SESSION variable to their number for in such a case because \$_POST does not carry on over several page views

Edited by SocialCloud
##### Share on other sites

This will do the computer guesses all in one shot - i.e. one page load - and display all the guesses and results. You can store the guesses in SESSION variables as suggested above and make the user click a button to see each guess one at a time.

```<?php

\$min = 1;
\$max = 100;
\$output = '';

function guessNumber(\$min, \$max)
{
return round((\$min+\$max) / 2);
}

if(\$_SERVER['REQUEST_METHOD']=='POST')
{
\$number = intval(\$_POST['number']);
if(\$number<\$min || \$number>\$max)
{
\$output = "<span style='color:red;'>You must enter a number from {\$min} to {\$max}.</span>";
}
else
{
\$output = "Your number was {\$number}.<br><br>\n";
\$min_guess = \$min;
\$max_guess = \$max;

\$guessNo = 1;
\$guess = guessNumber(\$min_guess, \$max_guess);
while(\$guess != \$number)
{
if(\$guess < \$number)
{
\$guessResult = 'low';
\$min_guess = \$guess + 1; //Set guess as new minimum
}
else
{
\$guessResult = 'high';
\$max_guess = \$guess - 1; //Set guess as new maximum
}
\$output .= "Guess number {\$guessNo} was {\$guess}. That was too {\$guessResult}.<br>\n";
\$guess = guessNumber(\$min_guess, \$max_guess);
\$guessNo++;
}
\$output .= "Guess number {\$guessNo} was {\$guess}. Correct!<br>\n";
}
}

?>
<html>
<body>
<form action="" method="post">
Enter a number between <?php echo \$min; ?> and <?php echo \$max; ?>:
<input type="text" name="number" />
<button type="submit">Submit</button>
</form>
<br><br>
<?php echo \$output; ?>

</body>
</html>```

As you requested this will be the most efficient method for finding the number by using the 50% rule. But, that's no fun for the user since any given number will always return the exact same guesses each time. I think it would be more entertaining for the user to add some variability. Plus, it would not be hard for the user to see what the computer is doing and to easily find numbers that would take longer for the computer to guess. There are two things you could do:

1. Make at least the first guess a random umber between the minimum and the maximum. So change the line before the while loop to this

`\$guess = rand(\$min, \$max);`

2. Or, you could make each guess a random between the "current" minimum and the "current" maximum. If a guess is to low, it becomes the new current minimum. So, if 15 was 'guessed' and found to be too low, the logic would never try to then guess a number that was 15 or less. It will continue to get closer to the number on each guess, but the guess would still be random. You could easily do this with the previous code, just change the function to this

```function guessNumber(\$min, \$max)
{
return rand(\$min, \$max);
}```

Edited by Psycho
##### Share on other sites

This will do the computer guesses all in one shot - i.e. one page load - and display all the guesses and results. You can store the guesses in SESSION variables as suggested above and make the user click a button to see each guess one at a time.

As you requested this will be the most efficient method for finding the number by using the 50% rule. But, that's no fun for the user since any given number will always return the exact same guesses each time. I think it would be more entertaining for the user to add some variability. Plus, it would not be hard for the user to see what the computer is doing and to easily find numbers that would take longer for the computer to guess. There are two things you could do:

1. Make at least the first guess a random umber between the minimum and the maximum. So change the line before the while loop to this

`\$guess = rand(\$min, \$max);`

2. Or, you could make each guess a random between the "current" minimum and the "current" maximum. If a guess is to low, it becomes the new current minimum. So, if 15 was 'guessed' and found to be too low, the logic would never try to then guess a number that was 15 or less. It will continue to get closer to the number on each guess, but the guess would still be random. You could easily do this with the previous code, just change the function to this

```function guessNumber(\$min, \$max)
{
return rand(\$min, \$max);
}```

This will make it sort of messy (at least what I will give as an example) and hopefully you can find a way to convert it to your liking

I would highly suggest setting \$_SESSION variables as yes this may cause an issue. The only ones I would give variables to is the computers random number and the counter. If a user were to view the source of the page they would see and could edit what their counter is, as well as the computer's number.

And in this method of the computer guessing I'm assuming you would need to have a continue or cancel button for the user to click, which I would set a \$_SESSION variable to their number for in such a case because \$_POST does not carry on over several page views

Thank you very much for the help with this code. I really do appreciate the help. It definitely makes sense the approach that you guys took to make this code work. For this particular instance I don't need to use session variables because the security isn't a risk, but I understand that it's better to do to prevent injection. Either way I appreciate all the help. I'll be sure ask if I have any other questions about this. Again I appreciate the time you took to help me out

##### Share on other sites

For this particular instance I don't need to use session variables because the security isn't a risk, but I understand that it's better to do to prevent injection.

What are you talking about? What security risk?

##### Share on other sites

There is no security risk, a user can only change the values in the field.

##### Share on other sites

There is no security risk, a user can only change the values in the field.

What are you talking about? What security risk?

oh ok, my bad, didn't quite grasp that one. So the only thing it prevents is them from changing the number is that what you're referring about?

Edited by xxplosions
##### Share on other sites

In the case of them guessing, they can change their guess, their counter, and the computer guess. they can also see those 3. In the case of the computer guessing, there's nothing important but you'll need some sort of \$_SESSION variable unless you use a loop

##### Share on other sites

```<?php
// for test purposes only:
set_time_limit(60);
\$_POST['guess'] = \$_GET['guess'];

function computer_guesses1(\$number){
\$min = 0;
\$max = 999;
\$guess = round(\$max-((\$max-\$min)/2));
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
function computer_guesses2(\$number){
\$min = 0;
\$max = 999;
\$guess = rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=rand(\$min,\$max)){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
function computer_guesses3(\$number){
\$min = 0;
\$max = 999;
\$guess = rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
function computer_guesses4(\$number){
\$min = 0;
\$max = 999;
\$guess = round(\$max-((\$max-\$min)/2));
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
function computer_guesses5(\$number){
\$min = 0;
\$max = 999;
\$guess = rand(0,1) ? round(\$max-((\$max-\$min)/2)) : rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=rand(0,1) ? round(\$max-((\$max-\$min)/2)) : rand(\$min,\$max)){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
if(!empty(\$_POST['guess']) && preg_match('/[0-9]{1,3}/', \$_POST['guess'], \$match)){
\$number = \$match[0];
// for test purposes only:
for(\$i=0; \$i<1000; \$i++){
computer_guesses1(\$i);
}
for(\$i=0; \$i<1000; \$i++){
computer_guesses2(\$i);
}
for(\$i=0; \$i<1000; \$i++){
computer_guesses3(\$i);
}
for(\$i=0; \$i<1000; \$i++){
computer_guesses4(\$i);
}
for(\$i=0; \$i<1000; \$i++){
computer_guesses5(\$i);
}
}
?>
```

Just for fun... ;o

But there are 5 different versions of basically the same script. What you asked for would be this one I think:

```function computer_guesses(\$number){
\$min = 0;
\$max = 999;
\$guess = rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
if(!empty(\$_POST['guess']) && preg_match('/[0-9]{1,3}/', \$_POST['guess'], \$match)){
computer_guesses(\$match[0]);
}```

When it comes to the user guessing the number. It must either be stored in a session/cookie or in a database (maybe file).

Edited by MMDE
##### Share on other sites

@MMDE When it comes to programming you have much to learn..

1) Your 5 functions can be reduced to 1 using callbacks:

```function computer_guess(\$number, \$guess_callback){
\$min = 0;
\$max = 999;
\$guess = call_user_func(\$callback, \$min, \$max);
for (\$guesses = 1; \$guess != \$number; \$guesses++, \$guess = call_user_func(\$callback, \$min, \$max)){
if (\$number < \$guess) {
\$max = \$guess-1;
} else {
\$min = \$guess+1;
}
}
return \$guesses;
}

echo 'Computer guessed the number 50 in ' . guess(50, function(\$min, \$max) { return round(\$max-((\$max-\$min)/2)); }) . ' guesses!';```

2) The logic in your function is flawed:

A )

`computer_guess1(1000);`

Creates an infinite loop as the computer will never be able to guess the number.

While a simple:

`if (\$number > \$max) return 'Does not compute!';`

Would have prevented that.

B )

If the user changes the max to a much higher number, say PHP_INT_MAX, it will take a very long time to find the number instead you should have used what is already mentioned

and what normal people tend to do, use 50% incr/decr to narrow down the range in which the number is located. Once you have located the proper range (answer 10 gives a higher, 15 gives a lower) should you do a last 50% and listen for the answer to know from which offset you need to decr/incr.

Edited by ignace
##### Share on other sites

@MMDE When it comes to programming you have much to learn..

1) Your 5 functions can be reduced to 1 using callbacks:

```function computer_guess(\$number, \$guess_callback){
\$min = 0;
\$max = 999;
\$guess = call_user_func(\$callback, \$min, \$max);
for (\$guesses = 1; \$guess != \$number; \$guesses++, \$guess = call_user_func(\$callback, \$min, \$max)){
if (\$number < \$guess) {
\$max = \$guess-1;
} else {
\$min = \$guess+1;
}
}
return \$guesses;
}

echo 'Computer guessed the number 50 in ' . guess(50, function(\$min, \$max) { return round(\$max-((\$max-\$min)/2)); }) . ' guesses!';```

2) The logic in your function is flawed:

A )

`computer_guess1(1000);`

Creates an infinite loop as the computer will never be able to guess the number.

While a simple:

`if (\$number > \$max) return 'Does not compute!';`

Would have prevented that.

B )

If the user changes the max to a much higher number, say PHP_INT_MAX, it will take a very long time to find the number instead you should have used what is already mentioned

and what normal people tend to do, use 50% incr/decr to narrow down the range in which the number is located. Once you have located the proper range (answer 10 gives a higher, 15 gives a lower) should you do a last 50% and listen for the answer to know from which offset you need to decr/incr.

I think it's more when it comes to reading you got much to learn...

It's like you didn't read the code at all... >_>

1. There are 5 functions so the person can see the different variations and see how they perform. No need for callback. Using callback here is very wrong when all I'm doing is showing him the 5 different variations.

2A. That would never happen...

```if(!empty(\$_POST['guess']) && preg_match('/[0-9]{1,3}/', \$_POST['guess'], \$match)){
\$number = \$match[0];```

I know he asked for between 1 and 1000, but again, just for test purposes, I wrote the regex to match between 0 and 999, hence why I used that in the code as well. The functions could easily be adjusted thereafter. No need to prevent when it will never happen, while not completely wrong to do what you are saying, it's pointless.

EDIT:

I believe this regex would suffice what he wants:

`'/1000|[1-9][0-9]{1,2}|[1-9][0-9]|[1-9]{1}/'`

2B. I don't get what you are talking about here, but I implemented what he request in the 3rd variant.

First it guesses a random number. Then it gets to know if its lower or higher. If it's higher then we know the number we are looking for is minimum the number we guessed +1. We then take max-((max-min)/2) and round it. This will end because of +1 and -1 with the max and min value.

```function computer_guesses(\$number){
\$min = 0;
\$max = 999;
\$guess = rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
```

^ It can be done as simple as that. It doesn't verify the number, it just assumes it is between 0 and 999. You can do this instead if you want it to verify all data and be more dynamic:

EDIT:

I made it like it was request, between 1 and 1000.

```function computer_guesses(\$number, \$min=1, \$max=1000){
if(\$number>\$max || \$number<\$min){
echo 'The number is too '.(\$number>\$max ? 'large' : 'small').'.<br />';
}
\$guess = rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
if(!empty(\$_POST['guess']) && preg_match('/1000|[1-9][1-9]{1,2}|[1-9]{1}/', \$_POST['guess'], \$match)){
computer_guesses(\$match[0]);
}
```

^ This one allows for the user to have typed in something else than just a number, but will only take the first valid number it finds.

Edited by MMDE
##### Share on other sites

There are 5 functions so the person can see the different variations and see how they perform. No need for callback. Using callback here is very wrong when all I'm doing is showing him the 5 different variations.

Are you really that ignorant? So you think there is a real valid reason for not generalizing your code when you have 5 similar functions with only the \$guess varying? >_<

2A. That would never happen...

```if(!empty(\$_POST['guess']) && preg_match('/[0-9]{1,3}/', \$_POST['guess'], \$match)){
\$number = \$match[0];```

Functions are re-usable components. This means you re-use the function not the code written around it. Therefor should your function always assume there was NO validation on the data passed through.

No need to prevent when it will never happen

LOL

```// no need to bother to prevent sql injection, it will never happen! MMDE said so!
\$sql = "SELECT * FROM users WHERE user = '\$user' AND pass = '\$pass';";
\$res = mysqli_query(\$conn, \$sql);
..
}```

2B.

You are right. I brain farted here because all your code is jammed against each other I guess.

Edited by ignace
##### Share on other sites

```function computer_guesses(\$number, \$min=1, \$max=1000){
if(\$number>\$max || \$number<\$min){
echo 'The number is too '.(\$number>\$max ? 'large' : 'small').'.<br />';
}
\$guess = rand(\$min,\$max);
for(\$guesses=1; \$guess!=\$number; \$guesses++, \$guess=round(\$max-((\$max-\$min)/2))){
if(\$number<\$guess) \$max = \$guess-1;
else \$min = \$guess+1;
}
echo 'Computer guessed the number '.\$number.' in '.\$guesses.' guesses!<br>';
}
if(!empty(\$_POST['guess']) && preg_match('/1000|[1-9][1-9]{1,2}|[1-9]{1}/', \$_POST['guess'], \$match)){
computer_guesses(\$match[0]);
}
```

^ This one allows for the user to have typed in something else than just a number, but will only take the first valid number it finds.

If I wanted to change the upper bound at all on the preg_match would I just change the 1000? Or would I have to do more than that? I've never really used preg_match at all so if you have a link that explains how it works that would be appreciated.

##### Share on other sites

Are you really that ignorant? So you think there is a real valid reason for not generalizing your code when you have 5 similar functions with only the \$guess varying? >_<

Functions are re-usable components. This means you re-use the function not the code written around it. Therefor should your function always assume there was NO validation on the data passed through.

LOL

```// no need to bother to prevent sql injection, it will never happen! MMDE said so!
\$sql = "SELECT * FROM users WHERE user = '\$user' AND pass = '\$pass';";
\$res = mysqli_query(\$conn, \$sql);
..
}```

You are right. I brain farted here because all your code is jammed against each other I guess.

I wrote 5 similar functions to show 5 different stand-alone functions. I did not try to use them at the same time, and they are not supposed to do so either. I suppose I could have written a way to compare these, that simply by putting them all in the same loop. They way of guessing was the variation. All I did was copy/paste them quickly.

I suppose the last one I posted is not good enough either to verify the data is a number, just to see if it is in range if it is a number.

With the code I wrote, it would never happen.... There would be no SQL injections. Read it, don't just act like a jerk. It takes only what matches the regex, only numbers. It doesn't care about the rest of the input from the user, because it doesn't use it. Neither is there any SQL connection in my code.

I think the biggest problem is this site's way of formatting code.

If I wanted to change the upper bound at all on the preg_match would I just change the 1000? Or would I have to do more than that? I've never really used preg_match at all so if you have a link that explains how it works that would be appreciated.

I guess this is a problem caused by me. I made the check dependent on regex. You need to understand what it does before you change it. o.O

It takes the first number that matches the pattern. The pattern is 1000 OR first character 1-9 the next two 0-9 OR first 1-9 the next one 0-9 OR the first is 1-9.

Edited by MMDE
##### Share on other sites

I wrote 5 similar functions to show 5 different stand-alone functions. I did not try to use them at the same time, and they are not supposed to do so either. I suppose I could have written a way to compare these, that simply by putting them all in the same loop. They way of guessing was the variation. All I did was copy/paste them quickly.

I suppose the last one I posted is not good enough either to verify the data is a number, just to see if it is in range if it is a number.

With the code I wrote, it would never happen.... There would be no SQL injections. Read it, don't just act like a jerk. It takes only what matches the regex, only numbers. It doesn't care about the rest of the input from the user, because it doesn't use it. Neither is there any SQL connection in my code.

I think the biggest problem is this site's way of formatting code.

I guess this is a problem caused by me. I made the check dependent on regex. You need to understand what it does before you change it. o.O

It takes the first number that matches the pattern. The pattern is 1000 OR first character 1-9 the next two 0-9 OR first 1-9 the next one 0-9 OR the first is 1-9.

Also, it seems I didn't use the same regex in both the edits...

`'/1000|[1-9][0-9]{1,2}|[1-9]/'`

It looks for matches in this order:

1000 (1000)

OR

first character is between 1 and 9, the second and maybe third is between 0-9 (10-999)

OR

first character is between 1 and 9 (1-9)

`preg_match(\$input, \$regex, \$matches);`

Looks for matches of the regex pattern in the input.

Stores them in \$matches

Stops after finding one match.

Returns the number of matches.

```// if any matches
if(preg_match(\$input, \$regex, \$matches)){
echo \$matches[0]; // the first and only match
}
```

Edited by MMDE
##### Share on other sites

Also, it seems I didn't use the same regex in both the edits...

`'/1000|[1-9][0-9]{1,2}|[1-9]/'`

It looks for matches in this order:

1000 (1000)

OR

first character is between 1 and 9, the second and maybe third is between 0-9 (10-999)

OR

first character is between 1 and 9 (1-9)

So for instance if I wanted 1-100 would it be as follows or am I understanding that incorrectly?

`'/100|[1-9][0-9]{1}|[1-9]/'`

##### Share on other sites

I wrote 5 similar functions to show 5 different stand-alone functions.

Which could have been reduced to 1 and still make your point.

I did not try to use them at the same time, and they are not supposed to do so either.

Where would I have implied they would have to be used at the same time? You can't run functions in parallel you know?

I could do the same you did by doing this, without duplicating code:

```function computer_guess(\$number, \$callback) {
..
}

function computer_guess1(\$number) {
return computer_guess(\$number, function(\$min, \$max) { /* rand strategy #1 */ });
}

function computer_guess2(\$number) {
return computer_guess(\$number, function(\$min, \$max) { /* rand strategy #2 */ });
}

..```

There would be no SQL injections.

It was an example to prove my point: "never make assumptions" and don't think: "it will never happen" because it will! Functions are re-usable components leaving input validation to the outer code means your code could break at some point when the function is re-used and input validation is forgotten before calling your function not to mention that you have to copy the validation code over and over again whenever you use the function.

Read it, don't just act like a jerk.

This is nothing personal. You made a mistake and I called you on it just like you called me on my mistake with your rand strategy with the sole goal of learning. I just wanted to show you that in order to write robust software your functions should perform the input validation not the calling code for the obvious reason you are otherwise copying or will have variations in validation across your codebase.

So for instance if I wanted 1-100 would it be as follows or am I understanding that incorrectly?

If you want 1 to 100 you do it like this:

`if (\$number >= 1 && \$number <= 100) {`

Don't use preg_match for something the programming language can do.

Edited by ignace
##### Share on other sites

Which could have been reduced to 1 and still make your point.

Where would I have implied they would have to be used at the same time? You can't run functions in parallel you know?

I could do the same you did by doing this, without duplicating code:

```function computer_guess(\$number, \$callback) {
..
}

function computer_guess1(\$number) {
return computer_guess(\$number, function(\$min, \$max) { /* rand strategy #1 */ });
}

function computer_guess2(\$number) {
return computer_guess(\$number, function(\$min, \$max) { /* rand strategy #2 */ });
}

..```

It was an example to prove my point: "never make assumptions" and don't think: "it will never happen" because it will! Functions are re-usable components leaving input validation to the outer code means your code could break at some point when the function is re-used and input validation is forgotten before calling your function not to mention that you have to copy the validation code over and over again whenever you use the function.

This is nothing personal. You made a mistake and I called you on it just like you called me on my mistake with your rand strategy with the sole goal of learning. I just wanted to show you that in order to write robust software your functions should perform the input validation not the calling code for the obvious reason you are otherwise copying or will have variations in validation across your codebase.

If you want 1 to 100 you do it like this:

`if (\$number >= 1 && \$number <= 100) {`

Don't use preg_match for something the programming language can do.

What part of "Just for fun... ;o" did you not understand? It was never meant as a robust re-usable component or anything like that, just to show the idea behind the code. Which is also why I wrote 5 different ones. It's just meant as examples and things to continue work on for him. I'm not here to do his work.

This is what I react to:

@MMDE When it comes to programming you have much to learn..

Are you really that ignorant?

LOL

```// no need to bother to prevent sql injection, it will never happen! MMDE said so!
\$sql = "SELECT * FROM users WHERE user = '\$user' AND pass = '\$pass';";
\$res = mysqli_query(\$conn, \$sql);
..
}```

You are right. I brain farted here because all your code is jammed against each other I guess.

^ You are not correcting me at any point here, you're being nothing but a jerk. Your "points" are lost in the way you write it. It seems you are more eager to tell me I'm wrong and insult me than actually trying to write something useful for the user.

Edited by MMDE
##### Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.