I am trying to convert a text file into a string, then into an array and then finaly print each of the values (words) into separate 'a' holders.
The .txt file contains one line of text.
I have tried it through a for loop, like so:
$lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
for ($x = 1; $x >= 100; $x++){
print '<a id="word$x">'$words[$x]'</a>';
}
But that doesnt work. I am sure that I am just missing something basic, but I have tried and failed so many times, that I need others opinions and advice.
At first, don't forget about string concatenation: print '<a id="word'.$x.'">'.$words[$x].'</a>';
If you need more, than only 100 words use $x < count($words)
in your for
You have to use <= instead of >=
for ($x = 1; $x <= 100; $x++){
print '<a id="word$x">'$words[$x]'</a>';
}
You can use sprinf, it's much easier to read.
$lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
for ($x = 1; $x >= 100; $x++){
echo sprintf('<a id="word%s">%s</a>', $word, $words[$x]);
}
But if you don't want to, you can simply concatenate the values.
echo '<a id="word' . $x . '">' . $words[$x] . '</a>';
It is a bad practice to use explicit for
loops.
$lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
$words = array_slice($words, 0, 100);
foreach ($words as $index => $word) {
print "<a id=\"word$x\">$word</a>";
}
Also, be aware array indexing starts with 0
not 1
. If you do $x = 1
you will end up losing the first word!
If you want to print all words, just lose the $words = array_slice($words, 0, 100);
. Read more about array_slice
here.