Fork me on GitHub

The PHP list() Construct

This is going to start out as a rant and end as a mini-tutorial, so let's get started.

I hate explaining the php list() construct to programmers who should know how to use it. I'm well aware that there are many, many, many functions and constructs in php and there is no plausable way to know them all. But list(), I mean, come on. That is a basic one!

Let's work on the premise that we have a csv file with fields containing: First Name, Last Name, City, State, and Birthdate. In your php script you import that data and break it into an array of records called $records. How many times have you seen code that looks something like this:

foreach($records as $record){
    //break each record into useable variables
    $temp_array = explode(',',$record);
    $first_name = $temp_array[0];
    $last_name  = $temp_array[1];
    $city       = $temp_array[2];
    $state      = $temp_array[3];
    $birthdate  = $temp_array[4];
    //Do something wil user data ...

Maybe I'm just picky, but that's no way to do that.

If you've never used the list() construct in php, I'm going to save your supervisor some heartache and teach you to use it. list() is not really a function, it's a language construct like array(). list() allows you to assign values to a group of variables as though the were an array. list() takes a list of variables as paramters and gets is assignment from an array. Here is an example from the php manual:

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

I really prefer to use list() in conjunction with the explode() function. The above (poor) example from the csv record is a great place to use list(). Here is that example slightly reworked:

foreach($records as $record){
    //break each record into useable variables
    list($first_name,$last_name,$city,$state,$birthdate) = explode(',',$record);
    //Do something wil user data ...

Now, isn't that sooo much nicer.

I'llĀ give one more example. I often encounter database fields with a comma separated list of parameters and I only want a couple of them, or I find a record out of a csv file that I only need a few fields out of. With list(), I can do something like:

fields in the csv are:
userid, first name, last name, height, weight, hair color, birthdate

list( , , $last_name, , , , $birthdate) = explode(',',$csv_record);

See, isn't that just cool. I'm amazed every day at the number of times that I see places where list() should have been used, and wasn't.

Anyway ...

If you don't use the list() construct, start now. If you do use it, good for you!

That's all ... hope you learned something ...