I am trying to program a Flat File PHP Dictionary (English -> Spanish).
I've got this up to now:
<?php
$data =
'car;coche
cat;gato
fat;gordo
far;lejos';
if($data) {
$line = explode("
", $data);
for($i = 0; $i<count($line); $i++) {
$item = explode(";", $line[$i]);
if($_GET['word'] == $item[0]) { echo"<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>"; }
else {echo MAIN PAGE;}
}
}
?>
It is perfect because it opens a loop of pages in one php file:
e.g. http://localhost/?word=fat
prints "Fat Gordo"
My problem is when creating the main page http://localhost. I tried with else{ echo "MAIN PAGE";}
but, wherever I place it, it prints "MAIN PAGEMAIN PAGEMAIN PAGE".
Any help?
that's because you are looping through every line in $data
. Whatever the outcome of the if expression is, after that it just goes on to the next iteration and runs the if statement again.
So if you add the } else { echo "mainpage"
to your if, it will echo mainpage
everytime when $_GET['word']
doesn't match $item[0]
(which obviously at every line if $_GET['word']
is not defined)
To avoid this you can add something like this:
if($data && !empty($_GET['word'])) {
(...)
} else {
echo "mainpage";
}
If you have a big dictionary it's also good to break you loop once you have found a matching word:
if($_GET['word'] == $item[0]) {
echo "<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>";
break;
}