This wiki is for the exclusive use of my friends and colleagues. Account creation and anonymous editing have been turned off.

If you are a friend or colleague of mine, and would like to participate in this project, please send me a message.

If you find these pages useful, please donate to help cover server costs. Thanks!

Explode() (PHP Function)

From OdleWiki
Php-med-trans.png

This page describes documentation valid for PHP 4 and PHP 5.

The explode() function is used to convert strings into arrays.

Syntax

The syntax for explode() is

$array = explode (separator , $string);

The separator must be contained within the string that is being converted to an array. For example, in this string

$days = 'Sunday - Monday - Tuesday - Wednesday - Thursday - Friday - Saturday';

the separator is " - " (including the spaces). To convert that string into an array, we would use

$days_array = explode(' - ' , $days);

The $days_array variable is now a seven-element array, with Sunday indexed at 0, Monday indexed at 2, etc.

Alternate Separators

The separator need not be a letter, number, or mark of punctuation. In the following example, it is simply the newline mark:

$days = 'Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday';

$days_array = explode("\n" , $days);

The effect is the same, except that larger arrays are easier to keep track of in this way. This is especially useful for compiling lists of responses that will be returned at random or in response to user input.

Optional Parameters

The function explode() takes an optional third parameter, which is a number limiting how many array elements are created. For example, this script:

$days = 'Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday';

$days_array = explode("\n" , $days);

echo $days_array[0] . "<br />";
echo $days_array[1] . "<br />";
echo $days_array[2] . "<br />";
echo $days_array[3] . "<br />";
echo $days_array[4] . "<br />";
echo $days_array[5] . "<br />";
echo $days_array[6] . "<br />";

would return this output:

Php explore 001.png

However, the following script would reduce the number of entries created to four.

$days = 'Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday';

$days_array = explode("\n" , $days , 4);

echo $days_array[0] . "<br />";
echo $days_array[1] . "<br />";
echo $days_array[2] . "<br />";
echo $days_array[3] . "<br />";
echo $days_array[4] . "<br />";
echo $days_array[5] . "<br />";
echo $days_array[6] . "<br />";

Its output would be:

Php explore 002.png

Notice that all remaining data gets entered into the last element of the array. The remaining echo functions return errors. If using this method, it is recommended to use one greater than the number of elements you need, in order to avoid this issue.

Synonyms and Antonyms

The function join() is a synonym for explode()

The function implode() converts arrays into strings.