I need to include an external php file, then execute some code and finally include the final file But since the first file has the beginning of the foreach and the second file has the end of the foreach, it's not working:
master script:
if ($conditionMet) include('begin.php');
echo 'blablabla';
... do more stuff
if ($conditionMet) include('end.php');
begin.php:
foreach (array(1,2,3,4) as $id):
end.php:
endforeach;
Of course it doesn't work. I thought maybe because php would not know where to start looping at the foreach again after begin.php was included but it's not that because it works if I do this:
if ($conditionMet) eval('foreach (array(1,2,3,4) as $id):');
echo 'blablabla';
if ($conditionMet) eval('endforeach;');
Can't write the code like this with eval, I don't like using eval, plus I have more code to put in begin.php and end.php
UPDATE:
It seems there is confusion as to why I want to do this and the purpose of the code. I thought it would be better to simplify the code to get a straight solution but it looks like I only made it worse, so I'll explain more:
If you forget about the two if
the master script, the line echo 'bablabla;
is in fact a lot of code with a foreach loop in it as well that passes through an associative array and outputs correct html. The array would for instance be like that:
array(
array('product'=>'carrot', 'price'=>5),
array('product'=>'onion', 'price'=>4),
array('product'=>'apple', 'price'=>2)
);
Now on certain occasions, the array would be slightly different like such:
array(
array('product'=>'carrot', 'price'=>5, 'category'=>'vegetable'),
array('product'=>'onion', 'price'=>4, 'category'=>'vegetable'),
array('product'=>'apple', 'price'=>2, 'category'=>fruit')
);
This is when $conditionMet
is true, so in "begin.php", it rebuilds the array like such:
foreach ( regorganizeArray($productsArray) as $productsArray)
to become
array(
array(
array('product'=>'carrot', 'price'=>5, 'category'=>'vegetable'),
array('product'=>'onion', 'price'=>4, 'category'=>'vegetable'),
),
array('product'=>'apple', 'price'=>2, 'category'=>fruit')
)
);
then will display extra stuff for instance
<h4>vegetables</h4>
then it the rest of the master script is executed seamlessly with the master script just displaying the content of the array without even knowing there's a difference.
Finally, "end.php" ends the foreach.
Now you're probably all thinking that I should put the code of the master script in a function but there are several versions of it (themes) and they never do the exact thing. The ONLY thing that all the different versions of the master script have in common is that the input array is the same.
There you go, sorry for all the confusion, I would not be a really good teacher as I'm bad at explaining, but I hope this made things clearer.