PHP foreach or for loop for this purpose?

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.

I am using PDO's unnamed place holder, so your solution of using implode() is useless for me. The above piece of code is the demo not the actual code. – Ibrahim Azhar Armar Jun 5 at 9:36.

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).

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.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions