explode

PHP Logo

Using list() With explode() In PHP

8th September 2009 - 2 minutes read time

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: