Jump to content

in_array function not working PLEASE HELP !!


woocha

Recommended Posts

Logically,  I am pretty damn sure this should work, buy it isn't.  I am building a text file db driven 'are you human' test.  The test is of questions and answers.  To validate the answers, I am using the built in php in_array function.  Here is my code and I hope you guys can help me out:

 

<?php

if(isset($_POST['submit']))
{
$fp = fopen('questions.php','r');
$answer = $_POST['answer'];
$field2 = $_POST['array'];
echo $answer.'<br />';
echo $field2.'<br />';
$array = split ('-', $field2);
print_r($array);
echo '<br />';
echo $answer.'<br />';
	if (in_array($answer,$array))
		{
			echo 'passed';
		}
		else
		{
			echo 'failed';
		}
}
else{
$file = 'questions.php';
$lines = count(file($file));
$number = rand(1,$lines);

if (($number > 0) and ($number < $lines)) {
$fp = fopen('questions.php','r');
if (!$fp) {exit('ERROR! Unable to open questions database.');}

$count = 0;
while ($count != $number) {
	$count++;
	$line = fgets($fp, 1024);
	$fp++;
}

fclose($fp);
list ($field1, $field2) = split ('\|', $line);
}
if(!$field1){header ('Location: flat-test.php');}
?>
<h1>Are You Human Test</h1>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<label><?php echo $field1; ?></label>
	<input name="answer" />
	<input type="hidden" name="array" value="<?php echo $field2; ?>">
	<input name="submit" type="submit" value="SHOW" /> 
</form>
<?php
}
?>

 

My text file is:

Are you human? | yes-no-sure
Are you human-2? | bob-weave-stab

 

The script seems to work some times but not all the time.  Can anyone see what I am doing wrong?

 

 

 

I think the strings you are looking for still have white spaces on them.

 

Above this:

if (in_array($answer,$array))

 

Put this:

echo $answer . "<br>";
print_r($array);

 

And see if $answer is actually in $array wi

 

I test this with

$answer = trim($answer);

but that didn't work.  I think you might be on to something though.  The values that don't work seem to be the first and the last values of the array.  Strange!

if anyone else is looking to do something similar to this you might want to avoid trying to use an array(I COULDN'T FIGURE IT OUT).  You might think about using this instead:

 

if ( strstr( $field2, $answer ) )

 

keep the string as a string and search the string for the answer

Use regex to skip the white spaces

 

Change this part from:

list ($field1, $field2) = split ('\|', $line);

 

To:

preg_match("/(.+?)\s*\|\s*(.*)/", $line, $matches);
$field1 = $matches[1];
$field2 = $matches[2];

 

split() uses regex, but I can't figure out the flavor.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.