I am learning how to use PHP. I read a file content into an array and assign variable name for each index in the array.
For example:
$words = file("example.txt"); #each line of the file will have the format a, b, c , d
foreach ($words in $word) {
$content = explode(",", $word); #split a, b, c, d
list($a, $b, $c, $d) = $content;
do something
}
/* And now I want to read file, split the sentence and loop over the array again, but
the last statement will do something else different: */
foreach ($words in $word) {
$content = explode(",", $word); #split a, b, c, d
list($a, $b, $c, $d) = $content;
do something else different
}
What can I do to reduce this redundancy? As you can see, I cannot make a function because the last statement do something different to the array. But the process of reading file, splitting sentences, and assigning vars are the same
Thank you
I'm assuming you meant to type foreach($words as $word), with "as" instead of "in", but that's just a minor thing compared to the question.
You can certainly reduce the redundancy by storing the results of the explode calls:
$lines = Array();
foreach($words as $word) {
list($a,$b,$c,$d) = $lines[] = explode(",",$word);
// do something here
}
foreach($lines as $line) {
list($a,$b,$c,$d) = $line;
// do something else
}
This way you don't have to explode the line again.
Well, if you're just going to work with $a, $b, $c and $d, and leave $content intact, just list $content again to do something else different.
foreach ($words in $word) {
$content = explode(",", $word); #split a, b, c, d
list($a, $b, $c, $d) = $content;
// do something, and when you're done:
list($a, $b, $c, $d) = $content;
// do something else different.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With