PHP - how to convert list to array using explode()

In this article you will learn how to convert PHP string to array() by splitting the string using a delimiter (separator).

 

PHP convert string to array using separator 

In PHP, the explode() function is a built-in function that can be used to split a string into an array of substrings. The explode() function takes two arguments: the first argument is the delimiter, which is the character or string used to separate the substrings, and the second argument is the input string that you want to split.

Here is an example of using the explode() function to split a string of words separated by spaces into an array of words:

$string = "The quick brown fox";
$string_to_array = explode(" ", $string);
print_r($string_to_array);

 

You can also use the explode() function to split a string by a specific character, for example, a comma:

$list = "apple,banana,orange";
$list_to_array = explode(",", $list);
print_r($list_to_array);

It's important to note that if the delimiter is not found in the input string, the explode() function will return an array containing the input string as the only element, and if the delimiter is an empty string, it will return an array of single-character strings.

 

list to array using PHP:

In PHP, you can use the array() function to convert a list (or any other iterable) to an array. Here is an example of using the array() function to convert a list of numbers to an array:

$list = [1, 2, 3, 4, 5];
$array = array($list);
print_r($array);

Alternatively, you can use the [] notation, which is the short array syntax, to convert a list to an array in PHP. Here is an example of using the short array syntax to convert a list of numbers to an array:

$list = [1, 2, 3, 4, 5];
$array = [$list];
print_r($array);

Both of these examples will output an array containing the numbers 1, 2, 3, 4, 5.

 

Another way to convert a list to an array is by using the splat operator ...

$list = [1, 2, 3, 4, 5];
$array = [...$list];
print_r($array);

This method is useful when you want to convert an itterable into an array, for example, when you want to use a function that accepts an array as an argument and you have an iterator or generator.

It's also important to note that some functions also accept lists as input, for example list() and range() functions, so you can use them to create lists and then convert them to arrays.

 

 


Tags:

PHP

Share:

Related posts