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
explodecalls:This way you don’t have to
explodethe line again.