Friday, 10 August 2018

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.
  1. $address = '123 Fake Street, Town, City, PO3T C0D3';
  2. list($street, $town, $city, $postcode) = explode(',', $address);
You can now print out parts of the address like this:
echo 'Street: ' . $street . '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:
  1. $address = '123 Fake Street, , , PO3T C0D3';
  2. 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.

0 comments:

Post a Comment