Using list() With explode() In PHP

A simple way to convert a string into a set of variables is through the use of the explode() and list() functions. list() is a language construct (not really a function) that will convert an array into a list of variables. For example, to convert a simple array into a set of variables do the following:

list($variable1, $variable2) = array(1, 2);

In this example $variable1 now contains the value 1 and $variable2 contains the value 2. This can be adapted to use the explode() function to take a string and convert it into a set of variables. An example of this in use might be when dealing with addresses, simply explode the string using the comma and you have a set of variables.

$address = '123 Fake Street, Town, City, PO3T C0D3';
list($street, $town, $city, $postcode) = explode(',', $address);

You can now print out parts of the address like this:

echo 'Street: ' . $street . '<br />Post Code' . $postcode . '.';

The good thing about using this code is that even if part of the address isn't present you will still get a variable for that space. Altering the previous example to remove the town and the city like this:

$address = '123 Fake Street, , , PO3T C0D3';
list($street, $town, $city, $postcode) = explode(',', $address);

Has the effect of creating empty $town and $city variables. They should always be present as long as your address has the same number of parts.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.