this is really a silly question to ask but i would like to know for the below condition which loop will be best to use? foreach or for loop?
$ids = array(1,2,3,4,5);
$query = 'INSERT INTO blah(id) VALUES ';
for($i=1; $开发者_如何学Pythoni<=count($ids); $i++) {
$query .= ' ( ? , ?) , ';
}
OR
foreach($ids as $id) {
$query .= ' ( ? , ?) , ';
}
Foreach is more concise in this case.
Just use implode.
$ids = array(1,2,3,4,5);
$query = 'INSERT INTO blah(id) VALUES (';
$query .= implode(', ', $ids);
$query .= ');';
Thats a standard function and thus probably the best / most optimized way to do it.
Other than that, foreach
is specifically for this case so you don’t need to define a variable for counting purposes. Makes it more readable.
In the end, it does not have noticeable implications on performance so you are free to use whichever you want. It’s more about coding style and readability.
Foreach is definitely easier. However, if you want to access the keys of your values (your $i
), you can do it this way:
foreach($ids as $i => $id) {
....
}
This does also work great with arrays where the key is not numeric, e.g. associative arrays.
It doesn't really matter, however remember that arrays without specified keys will start at index 0
- not 1
like you assume in your first example.
Using foreach()
can be easier to read, however using for()
allows you easy access to previous/following elements if required without having to mix both flavors (i.e. using the current element without an index, other elements with an index).
精彩评论