Php print array with delimiter
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. Show 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.
The $list variable will now contain the string "1,2,3,4,5,6". However, things tend to become messy again when you have an array with empty items in it.
The $list variable will now contain the string "1,2,3,4,5,6,,". So to solve this issue we need to use the array_filter() function to clear out any blank array items before passing the output to the implode() function. The following example shows this in action.
The $list variable will now contain the string "1,2,3,4,5,6", which is the string we are looking for. Support Us!Please support us and allow us to continue writing articles. PHP program to combine the array elements into a string with given delimiter: The below program is to combine the array elements into a string with given delimiter using PHP implode() function. The PHP echo statement is used to output the result on the screen. An array is a single variable which can store multiple values at a
time. The PHP implode() function is used to get a string by combining the elements of an array. Output PHP is an open-source language that is used for server-side development and scripting. It is widely known and used for server-side development. It works efficiently with databases like MySQL, Oracle, Microsoft SOL Server, PostgreSQL, and many other popular databases. It also supports file handling and data encryption. It supports a varied number of primitive data types in PHP. The 8 data types provided in PHP are categorized into 3 types namely, pre-defined or scalar type, compound type, and special type. This article gives an insight into the conversion of string data type to array in PHP and the advantages of achieving this. Different Methods to Convert String to Array in PHPThere are various approaches, including in-built functions and manual approaches that are used to convert string to array in PHP.
The first method in this list is str_split(). This is an in-built PHP method that is used to convert a string into an array by breaking the string into smaller sub-strings of uniform length and storing them in an array. It does not use any kind of separator, it just splits the string. The syntax of the str_split() function is: str_split($initial_string, $splitting_length) Parameters
Return ValueThis function returns an array that contains the pieces of the original string. If the length that is passed to the function surpasses the length of the initial string, the function will return the whole string as one element, whereas if the length integer is less than one, the function will return false. ExampleInput:"Program" Output:Array ( [0] => P [1] => r [2] => o [3] => g [4] => r [5] => a [6] => m ) Input:"Programming Language" Output:Array ( [0] => Prog [1] => ram [2] => ming [3] => Lang [4] => uage ) The following example illustrates the working of the str_split() function to convert string to array in PHP. // define a string $my_string = 'Sample String'; // without passing length // length = 1 (by default) $my_array1 = str_split($my_string); // print the array echo "The array of default length elements is: "; print_r($my_array1); // s, a, m, p, l, e, s, t, r, i, n, g print(" // passing length as second argument // length = 3 $my_array2 = str_split($my_string, 3); // print the array echo "The array of length 3 elements is: "; print_r($my_array2); // sam, ple, str, ing ?>
In the above example, it initializes a variable $my_string1 with a string “Sample String”. It uses the str_split() method to convert the string to an array. The following expression passes the string to this method without passing the length argument. $my_array1 = str_split($my_string); By default, if you do not pass the length delimiter, it takes it as 1. So, it converts separate elements of the string into array elements. And the following expression passes 3 as the length delimiter, which converts the substring of length 3 into array elements. $my_array2 = str_split($my_string, 3);
The explode() function is another method of PHP that is used to convert a string into an array. Unlike the str_split() function, this function uses a separator or delimiter that needs to be passed as an argument to the function. This separator could be a comma (,), a dot (.), or anything. After splitting the string into smaller substrings, this function stores them in an array and returns the array. The syntax of the explode() function is explode($separator, $initial_string, $no_of_elements) Parameters
Return ValueThe explode() function returns an array that contains the string pieces as its elements. ExampleInput:explode(“ “, “Hello, what is your name?") Output:Array ( [0] => Hello, [1] => What [2] => is [3] => your [4] => name? ) Input:explode(“ “, “Hello, what is your name?", 3) Output:Array ( [0] => Hello, [1] => What [2] => is your name? ) Input:explode(“ “, “Hello, what is your name?", -1) Output:Array ( [0] => Hello, [1] => What [2] => is [2] => your ) The following example illustrates the working of the explode() function to convert string to array in PHP. // define a string $my_string = 'red, green, blue'; // passing "," as the delimiter $my_array1 = explode(",", $my_string); // print the array echo "The converted Sarray is: print_r($my_array1); // red, green, blue ?>
In the above example, you are converting a string containing three colors separated by a comma to an array. The comma “,” is passed to the explode() function as a delimiter to convert the string into array elements.
The preg_split() is also an in-built PHP function that is used to convert a string into an array by splitting it into smaller substrings. Just like the explode() function, it also uses a separator but the separator in this function is a pattern of regular expressions. The length of substrings depends upon the integer value known as a limit that is passed to this function. The syntax of the preg_split() function is : preg_split($pattern, $string, $limit, $flags) Parameters
Return ValueThe preg_split() function returns an array containing the substrings as its elements, separated by the pattern passed to the function. The following example illustrates the working of the preg_split() function to convert string to array in PHP. // define a string $my_string = 'hello'; // -1 -> no limit $my_array = preg_split('//', $my_string , -1, PREG_SPLIT_NO_EMPTY); // print the array echo
"The converted array is: print_r($my_array); // h, e, l, l, o ?> In the example depicted above, it converts the string “hello” into an array. It passes ‘-1’ as the limit argument, so there is no limit. The “//” is passed as the pattern to convert separate characters of the string into array elements.
The str_word_count() function is another in-built function. It is not used to split the string, but it gives information about the string, such as the number of characters in the string, and so on. The syntax of the str_word_count() function is: str_word_count ( $string , $returnVal, $chars ) Parameters
Return ValueThe return value of the function depends on the parameters that are discussed above. The following example illustrates the working of the str_word_count() function to convert string to array in PHP. // define a string $my_string = 'he2llo world'; // the character '2' will not be considered as word $my_array1 = str_word_count($my_string, 1); // print the array echo "The converted array is: print_r($my_array1); // he, llo, world // the character '2' is passed as the third argument $my_array2 = str_word_count($my_string, 1, 2); // print the array echo " print_r($my_array2); // he2llo, world ?> In the above example, the string “he2llo world” contains a character ‘2’ which is not considered as a word by default by the function str_word_count(). So, the following expression converts the string into an array and ‘2’ is omitted. $my_array1 = str_word_count($my_string, 1); When you pass the character ‘2’ as the third argument to the str_count_world() function, then it is considered as a word and included in the array.
The next method in this list through which you can convert a string into an array is by manually looping through the string. You will initialize a variable, let's say “i” as 0, and start a loop from ”i” until “i” becomes less than the length of the string. Inside the loop, you will store each word of the string in the array and increment the variable “i”. The following example illustrates the manual approach using a for loop to convert string to array in PHP. // define a string $my_string = 'hello world'; // declare an empty array $my_array = []; // traverse the string for ($i = 0; $i < strlen($my_string); $i++) { if ($my_string[$i] != " ") { $my_array[] = $my_string[$i]; } } // print the array echo
"The converted array is: print_r($my_array); // h, e, l, l, o, w, o, r, l, d ?>
In the above example, an empty array is initialized. The string “hello world” is traversed using a for loop and each character of the string is inserted into the array.
The json_decode() function is used to decode a JSON encoded string. JSON stands for JavaScript Object Notation. JSON is a standard format for exchanging or transferring data and is powered by JavaScript. The JSON string usually represents the objects into data-value pairs. The syntax of the json)decode() function is: json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 ) Parameters
Return ValueThis function returns the decoded JSON string. If the depth of the encoded string is deeper than the specified depth limit of the recursion, this function will simply return NULL. The following example illustrates the working of the json_decode() function to convert string to array in PHP. // define a string $my_string = '{"h":2, "e":5, "l":4, "l":8, "o":10}'; // convert into array $my_array = json_decode($my_string); // print the array echo "The converted array is: var_dump($my_array); ?> In the above example, the string “hello” is initialized in the JSON format. The function json_decode() accepts this string as an argument, decodes it, and converts it into an array.
The unserialize() function is another in-built PHP function. It is just the opposite of the PHP serialize() function. This function converts a serialized string that is passed as a parameter, back into its original form i.e., an array. The syntax of the unserialize() function is: unserialize( $serialized_array, $options ) Parameters
Return ValueThe return value could be a boolean, string, integer, float, or anything. The following example illustrates the working of the unserialize() function to convert string to array in PHP. // define a string $my_string = 'a:3:{i:0;s:1:"a";i:1;s:6:"sample";i:2;s:6:"string";}'; // convert into array $my_array = unserialize($my_string); // print the array echo "The converted array is: print_r($my_array); ?>
In the above example, a serialized string “ a sample string” is initialized. The unserialize() function accepts this string as an argument and unserializes this string and converts it back to the original array. Get access to 150+ hours of instructor-led training, 20+ in-demand tools and skills, 10 lesson-end and 4 phase-end projects, and more. Learn to build an end-to-end application withj exciting features in our Full Stack Web Developer - MEAN Stack Program. Grab your seat TODAY! |