PHP: How to Convert String to an Array [explode()]

PHP: How to Convert String to an Array [explode()]

Convert string or comma separated string to array in PHP; In this tutorial, you will learn how to convert a string, comma separated strings to an array in PHP using explode().

In PHP, converting a string into an array can be done using the explode() function. The explode() function is used to split a string into an array by a specified delimiter. This function is very useful when you need to process large amounts of data, such as a list of items separated by commas or a log file separated by new lines. In this article, you will learn how to use the explode() function to convert a string into an array in PHP.

How to Convert a String to Array in PHP

The explode() function is a built-in function in PHP that allows you to easily convert a string into an array. It works by taking a string and splitting it into an array using a specified delimiter. The resulting array contains each segment of the original string that was separated by the delimiter.

  • What is explode function
  • Syntax of Explode Function
  • Example 1: Converting a Comma Separated String to an Array
  • Example 2: Converting a New Line Separated String to an Array
  • Example 3: Converting a Pipe Separated String to an Array
  • Example 4: Convert a String to an Array with a Different Delimiter
  • Example 5: Convert a String with Multiple Delimiters to an Array
  • Example 6: Convert Query String to an Array

What is explode function

PHP explode is a versatile string function that allows you to break a string into an array of substrings based on a specified delimiter. The delimiter can be a single character or a multi-character string, and the resulting array contains all the substrings between the delimiters. This function is useful for manipulating and processing data that is stored as delimited strings, such as CSV files or database records. By using PHP explode, you can easily extract specific information from these strings and work with it in a more meaningful way.

Syntax of Explode Function

The explode() function takes two parameters: the delimiter and the string to be split. The delimiter parameter specifies the character or sequence of characters that will be used to split the string into an array. The string parameter is the string that will be split into an array. Here is the basic syntax of the explode() function:

array explode ( string $delimiter , string $string , int $limit = PHP_INT_MAX )

The parameters are:

  • delimiter: Specifies the character(s) or string(s) that you want to use as a delimiter.
  • string: Specifies the string that you want to convert to an array.
  • limit (optional): Specifies the maximum number of elements that the array can have.

Example 1: Converting a Comma Separated String to an Array

Suppose you have a string that contains comma-separated values and you want to convert it into an array. In this example, you will use the explode() function to create an array of substrings separated by commas.

$string = "apple, banana, cherry, date, elderberry";

To convert this string into an array, you will use the explode() function and specify the comma as the delimiter:

$array = explode(",", $string);

The resulting array will look like this:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => date
    [4] => elderberry
)

Example 2: Converting a New Line Separated String to an Array

In this example, you will convert a new line separated string into an array using the explode() function. Suppose you have the following string:

$string = "This is the first line.\nThis is the second line.\nThis is the third line.";

To convert this string into an array, you will use the explode() function and specify the new line character as the delimiter:

$array = explode("\n", $string);

The resulting array will look like this:

Array
(
    [0] => This is the first line.
    [1] => This is the second line.
    [2] => This is the third line.
)

Example 3: Converting a Pipe Separated String to an Array

In this example, you will convert a pipe-separated string into an array using the explode() function. Suppose you have the following string:

$string = "John|Doe|25|Male|USA";

To convert this string into an array, you will use the explode() function and specify the pipe character as the delimiter:

$array = explode("|", $string);

The resulting array will look like this:

Array
(
    [0] => John
    [1] => Doe
    [2] => 25
    [3] => Male
    [4] => USA
)

Example 4: Convert a String to an Array with a Different Delimiter

You can use any character or string as a delimiter to split a string into an array. In this example, you will use a hyphen as a delimiter.

$string = "apple-banana-orange-grape";
$array = explode("-", $string);
print_r($array);

The first line of the code sets a string variable named $string to the value “apple-banana-orange-grape”.

The second line of the code uses the explode() function to split the $string variable into an array named $array. The delimiter used to split the string is the hyphen (“-“), which is passed as the first argument to the explode() function.

The third line of the code prints the resulting $array variable using the print_r() function, which displays the contents of the array in a human-readable format.

The output of this code would be:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

In summary, the explode() function is used to split a string into an array using a specified delimiter. In this example, the string “apple-banana-orange-grape” was split into an array containing four elements, separated by the hyphen (“-“).

Example 5: Convert a String with Multiple Delimiters to an Array

You can also split a string into an array using multiple delimiters. In this example, you will use both a comma and a hyphen as delimiters.

$string = "apple-banana,orange-grape";
$array = preg_split("/[-,]/", $string);
print_r($array);

The given code demonstrates the use of preg_split() function in PHP to split a string into an array using a regular expression pattern as a delimiter.

Let’s break down the code step by step:

  1. $string = "apple-banana,orange-grape"; – This line initializes a string variable $string with the value “apple-banana,orange-grape”.
  2. $array = preg_split("/[-,]/", $string); – This line uses the preg_split() function to split the $string variable into an array $array. The regular expression pattern used as a delimiter in this function is "/[-,]/". This pattern specifies that the string should be split at either the hyphen (“-“) or comma (“,”) character. The resulting array will contain the segments “apple”, “banana”, “orange”, and “grape”.
  3. print_r($array); – This line uses the print_r() function to print out the resulting array $array.

The output of this code would be:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

In summary, the given code splits the original string “apple-banana,orange-grape” into an array of segments by using the preg_split() function with a regular expression pattern "/[-,]/" as a delimiter. The resulting array $array contains the segments “apple”, “banana”, “orange”, and “grape”.

Example 6: Convert Query String to an Array

To convert a query string to an array in PHP using explode(), you can first extract the query string from the URL using the $_SERVER['QUERY_STRING'] variable, and then split it into an array using the explode() function.

Here’s an example code snippet to demonstrate this:

$url = "https://example.com/?fruit=apple&color=red&quantity=3";
$query_string = parse_url($url, PHP_URL_QUERY); // extract query string
$array = explode('&', $query_string); // split query string into array

// loop through the array to split each key-value pair into separate variables
foreach ($array as $key_value) {
    list($key, $value) = explode('=', $key_value);
    $query_array[$key] = $value; // add key-value pair to the resulting array
}

print_r($query_array); // output the resulting array

To convert a query string to an array in PHP using explode(), you can first extract the query string from the URL using the $_SERVER['QUERY_STRING'] variable, and then split it into an array using the explode() function.

Here’s an example code snippet to demonstrate this:

phpCopy code$url = "https://example.com/?fruit=apple&color=red&quantity=3";
$query_string = parse_url($url, PHP_URL_QUERY); // extract query string
$array = explode('&', $query_string); // split query string into array

// loop through the array to split each key-value pair into separate variables
foreach ($array as $key_value) {
    list($key, $value) = explode('=', $key_value);
    $query_array[$key] = $value; // add key-value pair to the resulting array
}

print_r($query_array); // output the resulting array

In this example, the $url variable contains the URL with a query string. The parse_url() function is used to extract the query string from the URL and store it in the $query_string variable. The explode() function is then used to split the $query_string variable into an array of key-value pairs.

Finally, a foreach loop is used to split each key-value pair in the array into separate variables using the explode() function again. The resulting key-value pairs are added to the $query_array variable, which is the final array containing the parsed query string.

The resulting output of the print_r() function should be an associative array with the keys and values of the query string, like this:

Array
(
    [fruit] => apple
    [color] => red
    [quantity] => 3
)

Conclusion

The explode() function is a very useful tool in PHP for converting a string into an array. It allows you to easily split a string into an array using a specified delimiter. In this article, you have learned how to use the explode() function to convert comma separated, new line separated, and pipe separated strings into arrays. You can use this function to split any type of string into an array as long as you know the delimiter used in the string.

Recommended PHP Tutorials

  1. PHP Convert String to Array
  2. PHP Array: Indexed,Associative, Multidimensional
  3. To Remove Elements or Values from Array PHP
  4. PHP remove duplicates from multidimensional array
  5. Remove Duplicate Elements or Values from Array PHP
  6. Array Push and POP in PHP | PHP Tutorial
  7. PHP Search Multidimensional Array [key and value and return key
  8. php array to comma separated list
  9. PHP Remove Duplicate Elements or Values from Array PHP
  10. Reverse String in PHP

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *