Counting to 1000 in PHP without loops or conditionals

Posted March 14th, 2011 in PHP by Andrew Curioso

Update: added a benchmark for performance comparison and updated the code to no longer rely on a fatal error to exit.

It started with one question:

Print numbers from 1 to 1000 without using any loop or conditional statements. Don’t just write the printf() or cout statement 1000 times.

How would you do that using C or C++?
Source: Stack Overflow

My favorite answer was an amazing example of obscure C. Using math to iterate between two function pointers (printf and exit). And while it brought back memories of my C days, I kind of left it at that.

Later in the day, one of my co-workers messaged me with his version of a 1-1000 iterator in PHP. So naturally, I had to write my own version.

Continue Reading »

Error handling stack in PHP 5.3+

Posted October 13th, 2010 in PHP by Andrew Curioso

Update: this article is mentioned in a few places as a practical example of using closures.
Some languages pass variables into a closure automatically. In PHP it needs to be done explicitly using the use keyword. See line #6 of the code example.

I was inspired by a question that I was asked on Twitter to write a quick code snippet.

As you may know, set_error_handler can be used to set a custom error handler in PHP. It will catch any errors that happen in the script (with a few notable exceptions). If the function returns false then error handling resumes as normal; otherwise it is assumed that the custom handler took care of things. The problem is that you can only have one error handler active at one time. The purpose of this code is to provide a error handeling stack for PHP.

Using this code you can have more than one error handler while taking advantage of the set_error_handler function.
Continue Reading »

Detecting file size overflow in PHP

Posted June 9th, 2010 in PHP by Andrew Curioso

One of the things that separates a good web application from a great one is how gracefully they handle failures. One of the often overlooked cases is when a user attempts to upload a file that exceeds the set PHP upload file size. This article shows how to detect when the user tries to upload a file that is too large and display an appropriate message.
Continue Reading »

5 things about PHP 5.3 that make me smile

Posted June 30th, 2009 in PHP by Andrew Curioso

Rest assured. Soon I will be writing “Things about PHP 5.3 that make me cringe” but for now I sing the praises of the latest release of PHP that that came out today. I’ve been playing with the new release for months and there are indeed many good things about it and many of them have been a long time coming.

The other day I was reading the release notes and I couldn’t help but smile.
Continue Reading »