Getting the first or last item from an array in PHP is usually quite easy. If you create an array and then add a bunch of values to it then the array index will increment by 1 for every element you add. This means that in order to get the first element from an array you just reference the default stating position (0). To get the last item in the array the index key will be the length of the array, minus 1. Here is some example code showing this.
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:
I have previously talked about Removing commas from the end of strings, but it is also possible to use the implode() function to do the same sort of thing.
implode() takes two parameters, the separator and the array, and returns a string with each array item separated with the separator. The following example shows how this function works.
- $australian_states = array(
- "NSW"=>"New South Wales",
Use the following array to print out a list of Canadian states, also know as provinces.
Use the following array if you want to print out a list of USA states either as a list, or as a select box.
Converting an array of information into a string is easy, but when you are doing this for insertion into a database having trailing commas is going to mess up your SQL statements.
Take the following example, which takes an array of values and converts them into a string of values. This practice is quite common in PHP database manipulation.
Use the following code to create an array of counties in the UK.
Use the following function to remove all duplicate values in an array.
If you have an object or array that you want to save until a later you can use the serialize() and unserialize() functions. The operation of the functions are straightforward. To serialize() an array just pass the serialise function the array like this.