Friday, 19 September 2014

Answering my first PHP question on Stack Overflow

G'day:
It's really quite interesting. With any CFML question someone might ask me, I am brimming with confidence (or bravado, perhaps), am self-assured, and have no problem either backing myself to be correct, or happy to say "dunno, but I'll find out". I've decided I had better start answering PHP questions on Stack Overflow, as answering questions is a really good way to learn stuff. Especially if one doesn't know the answer to start with.

how do i search the array for the 10th key for example, and choose only the chunk its located in?

It's amazing how quickly answers appear for PHP questions - obviously it's a much bigger community than the CFML one - but I found the quality of answer to be about the same. Read into that comment what you will.

I spotted an "in" for using a technique that hadn't been mentioned yet, so I decided to answer.

The other thing... I had all sorts of problems getting the closure bit to work... because one has to tell PHP which variables to enclose!! Yikes.

Still: that works quite nicely, IMO, with the following caveat I put in my answer:

Note: this will return multiple chunks if there are multiple chunks with the same key in them (which is entirely possible, depending on your data structure).

If you definitely only wanted the first chunk which matched, array_filter() is possibly doing too much work, as it will traverse the entire outer array whether you need it to or not. That that might matter is down to how big your arrays are.

If performance was more important than clarity of intent, then using a more traditional conditional loop might be more the ticket.

I'm pleased PHP has these iteration functions. I haven't checked them all out yet, but I think I perhaps will, shortly.

Anyway: I half expected to get pilloried for my answer for some reason I just don't know about with PHP, but we'll see. I am moderately pleased I was actually able to answer a question though. Cool.

Search This Blog

About

I've been a web developer since 2001. I have spent 13yrs as a CFML developer, and until Sept 2014, that was the main subject matter here. I've now been re-tasked as a PHP developer, so learning PHP will become the focus of this blog. But I also mess around with other languages too.

I tend to be a bit "forthright" in my opinions, I am indelicate, and I tend to swear too much. This will come out occasionally here: I make no apology for it.

Everything said here is my own opinion. Feel free to disagree with me :-)