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.

Share:

  • Add news feed
  • Bookmark this on Delicious

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <h4> <h5> <h6> <pre> <span> <p> <br />
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.