When should you, and when should you not, use wp_list_pluck()?

In any foreach loop, the last value of the array being looped over remains after the end of the foreach loop. That is why one should actually always unset that value after the foreach loop is done.

wp_list_pluck() is also just a basic foreach loop if $index_key is not passed. Also, as with any foreach loop, the last value of the array remains after the end of the foreach loop, and I think this is what that line refers to in the codex.

However, that assumption is wrong. Functions are self contained pieces of code, and except for globals, these pieces of code inside a function are only avaiable to the function itself. wp_list_pluck() does not globalize any of its intenal values (variables), so even if the last value of the array is still available after the foreach loop inside the function, and does not get unset, it is not available to any piece of code outside the function, so you cannot have the pass-by-reference issue as described in that line in the codex.

wp_list_pluck() is as valid to use as any simple foreach loop. The choice is up to you. I personally prefer wp_list_pluck() as it saves on code, and you do not need to remember to unset variables which can later lead to debugging nightmare.

Just a final note, wp_list_pluck() can also replace array_column as it works the same if $index_key is passed to the function

Leave a Comment

tech