Php pass string to array

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

  • 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
Читайте также:  Java runtime app jar

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 )
  • 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:

Читайте также:  Javascript write to document with html

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:

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:

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

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.

  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.

Author Admin

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.

Источник

How to add a string value into a PHP array

The array_push is working as it is designed for.

It will add the value and returns the number of elements in that array.

so it is natural if it is returning 3 your array has 2 elements after array push there are now three elements.

You should print_r($array2) your array and look the elements.

$push = array_push($array2, $value); 

array_push() uses reference to the array for the first parameter. When you print_r() , you print the array $array2 , instead of $push .

You are printing the return value of array_push which is the number of items in the array after the push. Try this:

Really, you should be using $array2[] = $value; which will put the value in the first available numeric key in the array, rather than array_push() .

To get the value of the last element in the array(i.e. what you just added) and keep the array intact, use end($array) , or to get the last element and remove it from array, use array_pop($array)

array_push modifies $array2. $push contains count($array2).

In more modern days you could add strings or other data types to an array with Square Bracket method like this:

This approach will add the string ‘world’ to the $arr array variable.

Now the array will actually look like this [‘hello’, ‘world’] which is pretty neat, and quicker than array_push

array_push would be more suitable if you were to push more than one element into the array.

Im pretty confident that Square Bracket Method was introduced in PHP 5.4

Источник

Оцените статью