Reputation: 833
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
Upvotes: 3
Views: 495
Reputation: 31813
There's LOTS of variations. The tricky part is identifying the generic parts that can be abstracted away. Sometimes you make your code worse by trying to make it too generic. But here's a sample using anonymous functions.
function foo($filename, $func) {
$words = file($filename);
foreach ($words as $word) {
$content = explode(",", $word);
call_user_func_array($func, $content);
}
}
foo('people.txt', function($a, $b, $c, $d) {
echo "$a\n";
});
foo('people.txt', function($a, $b, $c, $d) {
echo $b + $c;
});
you might also be intrested in array_map, array_walk, and array_reduce, although I personally don't feel theyre often better than a loop... php's foreach is pretty darn awesome.
Upvotes: 0
Reputation: 6902
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.
}
Upvotes: 1
Reputation: 324630
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.
Upvotes: 2