FlyingUnderpants FlyingUnderpants - 2 months ago 7
PHP Question

Search futher if the amount of digits a number has is > 1

I'm learning PHP and started a small project with some file handling involved, a database checker on numbers (to keep it simple). What I mean by that is when you type in a number and hit the submit button php is going to search through a text file to get a name by the number.

The text file looks like:

1 Sandra

2 Piet

3 Francis

etc...

The code:

<?php
// Type your code here
$val = $row = NULL;


if (isset($_POST["submit"])) {
$myFile = fopen("testData.txt","r");
$number = $_POST["input"];
$cntNumber = strlen($number);



while (!feof($myFile)){
$val = fgetc($myFile);

if (is_numeric($val)) {
if ($cntNumber > 1) {
// Point where I Don't know what to do
} elseif ($val == $number) {
$row = fgets($myFile);
}

}
}
}

?>

<div style="width: 232px; height: 100px; border: 1px solid gray; margin-bottom: 5px;">
<?php
echo $row . "<br>";
?>
</div>
<form action="index.php" method="post">
<input name="input" placeholder="Number" type="text">
<input name="submit" value="Search" type="submit">
</form>


So if the number has more than one digit it has to search for the next matching digit, but I don't know how I can achieve that. I hope my explanation was clear enough, if not don't mind asking some question's.

Thanks in advance

Answer

I don't know whether you want to use f-file functions, but simplier solution is:

if (isset($_POST["submit"])) {
    $myFile = file("testData.txt");
    // print_r $myFile and see that this is array of lines

    $number = $_POST["input"];
    // iterate over your lines:
    foreach ($myFile as $line) {
        // as each line contains two values divided by a space, 
        // you can explode the line into two parts
        $parts = explode(' ', $line);
        // print_r($parts) to see result

        // next check first part which is number:
        if ($parts[0] == $number) {
            echo 'Found!';
            break;    // exit loop as your value is found
        }
    }
}

If you want to use f-file functions then code can be:

$fh = fopen("testData.txt", "r");
while(!feof($fh)) {
    $str = fgets($fh, 1024);
    $parts = explode(' ', $str);
    // print_r($parts) to see result
    if ($parts[0] == $number) {
        echo 'Found!' . $str;
        break;    // exit loop as your value is found
    }
}

But I strongly recommend you to use databases as storages.

Comments