I’ve been brushing up on my PHP basics lately. Why? Well, it never hurts to revisit things you think you already know. There is a good chance you will discover something you didn’t know after all. For example: this time I learned about PHP’s
extract takes an associative array and creates local variables on the fly, named for the keys in the array and with the corresponding values matched up.
compact is the corresponding function for taking a collection of variables and stuffing them into an associative array.
Running this code:
extract is the more immediately useful of the two for my purposes, because it simplifies a common tactic I use for creating local variables based on database lookups.
Instead of manually creating local variables, like this:
I can save myself a little effort with
I realize that there may be an even easier way to do it, but just this will make my life noticeably easier as long as I don’t abuse it. I would mainly tuck a call like this off in a function and probably use it in conjunction with a SQL query or something else where I knew exactly what names I would end up with.
Why didn’t I know about this before? Well, the manual approach was good enough. And since what I had was good enough, I didn’t think of looking for a better approach. Then again, finds like this are exactly why I do go back and review what I thought I already knew.
Added to vault 2024-01-15. Updated on 2024-01-26