Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php foreach loop redundancy

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

like image 845
kaboom Avatar asked Jun 18 '26 01:06

kaboom


2 Answers

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.

like image 137
Niet the Dark Absol Avatar answered Jun 19 '26 13:06

Niet the Dark Absol


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.
}
like image 39
Parziphal Avatar answered Jun 19 '26 14:06

Parziphal