Archive for December, 2006

PHP foreach loops pass arrays by value

Sunday, December 17th, 2006

I nearly lost my mind debugging a problem with some PHP I’d written awhile back that wasn’t working as I’d expected on one server (but fine on my own.)

After many hours of cursing myself for not having a better debugging system, I discovered it was a PHP 4 versus PHP 5 code incompatibility. Turns out that PHP passes arrays into foreach loops by value, which means that any changes you make to that array inside the foreach don’t appear after the foreach, because it’s acting on a copy of the arrray instead of the original data.

So code like this:

Doesn’t print “nothingnothing”, which is what I’d expect; it prints “rainbowspuppies.” In PHP4, apparently, there’s no way to get around this. In PHP5, you can pass the array into the foreach by reference using this notation: foreach ($gina->interests as & $interest)

For now, I to make my code both PHP4 and PHP5 compatible, I went with a:

while ($i=0; $i < sizeof($gina->interests); $i++)

Which just isn’t as readable as the foreach. Here’s the PHP doc on foreach (which clearly states the PHP 5 caveat.)

Sunday, December 3rd, 2006

Here’s a handy tip on how to track broken links or missing pages on your site with Google Analytics. Speaking of, here’s how we use Analytics at Lifehacker to figure out which posts are our top performers.

Graphing Amazon sales rank, or automated author navel-gazing

Saturday, December 2nd, 2006

Like most authors tasked with promoting their new book, checking Lifehacker the book’s Amazon sales rank has become part of my daily routine. But your book’s sales rank is one of those things - if you obsess about it too much, you’ll lose your mind. “It’s total B.S.,” a writer friend told me. “My agent told me it’s a miniscule representation of your book’s sales overall.” That’s probably less true for tech books than fiction, but either way, I wanted a way to capture my sales rank over time without constantly checking myself like an anxious freak. A number alone after awhile is pretty meaningless, and it literally changes by the hour.

So, inspired by PB’s graphing post and a curiosity about Amazon’s API, I set out to write a little something that would help me visualize what’s happening with the book’s sales over time. I didn’t get into the hardcore tools Paul did - just the names RRDTool or SNMP scare me - so I instead opted for the very no-frills, Flash-based PHP/SWF graphs. After registering for a free key, I was delighted to find that the Amazon API is dead simple. In less than 30 minutes of a little PHP/MySQL hacking, I had a sales rank capture-and-graph set of PHP scripts. It’s turned out to be a really nice way to keep an eye out without reloading the book’s Amazon page 4 times a day like a total egotistical loser.

Here’s the finished Lifehacker book Amazon sales rank charter. Screengrab below:

Amazon sales rank charter