I was just asking myself what is faster: I have a for loop where I have to check a certain table column against my loop variable.
Now I have two options: Within the loop I fire a query for each iteration and check my results. The second option is to fetch all the rows I need, and within my for-loop I run a foreach-loop and check if I have a valid match between my desired field and my loop variable.
It's a bit hard to explain but I just let the code speak. I don't use real code here within the loops but fictional function calls by way of illustration.
Option 1: Querying the database for each iteration.
<?php
// Option 1:
for($i = 0; $i < 5; $i++)
{
$query_result = query_database_where_field_equals($i);
if($query_result)
{
echo "Here is something";
}
else
{
echo "Here is nothing";
}
}
// Option 2:
$results = query_database_and_get_all_results();
for($i = 0; $i < 5; $i++)
{
foreach($results AS $result)
{
if($result['desired_field'] == $i)
{
echo "Here is something";
}
else
{
echo "Here is nothing";
}
}
}
?>
Both ways will work, but I'm pretty sure it's a worse practice to fire queries within a loop in a performant point of view.
But using a foreach loop within the for-loop also seems to be a bit odd to me.
So what is the prefered way of doing this?
Edit - Added information
I have a for loop that needs to run several times. The amount is static (e.g. 5) and does not depend on any records in the database. Each iteration represents a position.
I have a database table which might store information about what a position contains.
Example:
positions (id, position)
So an example record might be: positions (1, 2)
That means that I have something on position 2. What I want to do in my loop basically is, to check whether I got a record for that position or not. Expected output would be:
Here is nothing
Here is nothing
Here is something
Here is nothing
Here is nothing