PHPIt is an open source language used for server-side development and scripting. It is widely known and used for server-side development. Works efficiently with databases likeMySQL, Oracle, Microsoft SOL Server,PostgreSQLName, and many other popular databases. It also supports file manipulation anddata encryption.
It supports a number of primitive data types in PHP. The 8 data types provided in PHP are categorized into 3 types i.e. predefined or scalar type, composite type and special type. This article provides an insight into the conversion ofstring data typeformatrix in PHPand the advantages of achieving this.
Different methods to convert string to array in PHP
There are several approaches, including integrated systemsfunctionsand manual approaches that are used to convert string tomatrix in PHP.
-
str_split() function
The first method in this list is str_split(). This is a PHP built-in method that is used to convert a string to an array by breaking the string into smaller substrings of uniform length and storing them in an array. It doesn't use any kind of separator, it just splits the string.
The str_split() function syntax is:
str_split($initial_string, $splitting_length)
parameters
- $initial_string (required): The first parameter you pass to this function is the string that is to be converted into an array.
- $splitting_length (optional): The second parameter is an integer representing how long the string parts will be after splitting. It is an optional parameter. If not passed, the function will consider this length as 1 by default.
return value
This function returns an array containing the pieces of the original string. If the length passed to the function exceeds the length of the initial string, the function returns the entire string as one element, while if the integer length is less than one, the function returns false.
Example
Prohibited:
"Program"
Exit:
Variety
(
[0] => P
[1] => r
[2] => o
[3] => g
[4] => r
[5] => one
[6] => m
)
Prohibited:
"Programming language"
Exit:
Variety
(
[0] => Program
[1] => sheep
[2] => min
[3] => Lang
[4] => uage
)
The following example illustrates how the str_split() function works to convert a string into an array in PHP.
<?php
// define a string
$my_string = 'String example';
// without passing length
// length = 1 (by default)
$my_array1 = str_split($my_string);
// print the matrix
echo "The default length array of elements is: ";
print_r($minha_array1); // s, a, m, p, l, e, s, t, r, i, n, g
print("<br><br>");
// passing length as second argument
// length = 3
$my_array2 = str_split($my_string, 3);
// print the matrix
echo "The array of length 3 elements is: ";
print_r($my_array2); // sam, ple, str, ing
?>
In the example above, it initializes a variable $my_string1 with a string “Sample String”. It uses the str_split() method to convert the string into 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 don't pass the length delimiter, it defaults to 1. So it converts separate string elements to array elements. And the following expression passes 3 as the length delimiter, which converts the substring of length 3 to array elements.
$my_array2 = str_split($my_string, 3);
Learn from the best mentors in the industry!
Master's Program in Test Automationexplore program
-
explode("DELIMITER", STRING);
The explode() function is another PHP method used to convert a string to 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 can be a comma (,), a period (.), 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
- $separator: The separator is a character that commands the explode() function to split the string whenever it detects the separator and stores that substring in the array.
- $initial_name: The second parameter that is passed to this function is the string that is to be converted into an array.
- $no_of_elements (optional): This is the last and optional parameter that is passed to this function. This parameter represents the number of strings into which to split the original string. This number can be positive, negative, or zero.
- Positive: If the integer passed is positive, the array will store that number of elements. If you split the string into more than N parts with respect to the delimiter, the first N-1 elements will remain the same and the rest of the elements will combine to form a single element.
- Zero: If the integer passed is 0, the array will contain the entire string as a single element.
- Negative: If the integer passed is negative then the last N elements of the array will be cut and it will return the remaining elements.
return value
The explode() function returns an array that contains the pieces of string as its elements.
Example
Prohibited:
explode(“ “, “Hello, what is your name?”)
Exit:
Variety
(
[0] => Hello,
[1] => What
[2] => is
[3] => your
[4] => name?
)
Prohibited:
explode(“ “, “Hello, what's your name?”, 3)
Exit:
Variety
(
[0] => Hello,
[1] => What
[2] => is your name?
)
Prohibited:
explode(“ “, “Hello, what's your name?”, -1)
Exit:
Variety
(
[0] => Hello,
[1] => What
[2] => is
[2] => your
)
The following example illustrates how the explode() function works to convert a string into an array in PHP.
<?php
// define a string
$my_string = 'red, green, blue';
// passing "," as delimiter
$my_array1 = explode(",", $my_string);
// print the matrix
echo "The converted sarray is: <br>";
print_r($my_array1); // red, green, blue
?>
In the example above, you are converting a string containing three colors separated by a comma into an array. The comma “,” is passed to the explode() function as a delimiter to convert the string into array elements.
Here's How to Get a Top Software Developer Job
Full Stack Development-MEANexplore program
-
preg_split() function
preg_split() is also a built-in PHP function that is used to convert a string to an array by splitting it into smaller substrings. Like the explode() function, it also uses a separator, but the separator in this function is a regular expression pattern. The length of the substrings depends on the integer value known as the limit that is passed to this function.
The syntax of the preg_split() function is:
preg_split($pattern, $string, $limit, $flags)
parameters
- $pattern: The pattern is a regular expression that determines which character is used as a separator to split the string.
- $string: The second parameter that is passed to this function is the string that is to be converted into an array.
- $limit (optional): The limit indicates the total number of substrings it will split the string into. If all separators appear before the end of the boundary, the elements (limit-1) remain the same and the rest of the elements combine to form the last element. If the limit is 0, it returns the entire string as a single element. However, it is an optional parameter. If not mentioned, it will consider the limit to be -1 by default.
- $flags (optional): This is an optional parameter. If passed, it is used to bring some changes to the array. In other words, the flag represents the condition under which the final array will be returned. These options or conditions are:
- PREG_SPLIT_NO_EMPTY: This type of flag is used to remove the empty string and non-empty strings will be returned.
- PREG_SPLIT_DELIM_CAPTURE: This type of flag is also used to get the delimiter in the resulting array. If this flag is used, the expression enclosed in parentheses will also be captured as an array element.
- PREG_SPLIT_OFFSET_CAPTURE: This type of flag causes the function to return a pair as an array element. The first part of the pair will be the substring and the next part of the pair will be the index of the first character of the substring in the initial string.
return value
The preg_split() function returns an array containing the substrings as its elements, separated by the pattern passed to the function.
The following example illustrates how the preg_split() function works to convert a string into an array in PHP.
<?php
// define a string
$my_string = 'hello';
// -1 -> no limit
$my_array = preg_split('//', $my_string , -1, PREG_SPLIT_NO_EMPTY);
// print the matrix
echo "The converted array is: <br>";
print_r($my_array); // hello
?>
In the example described above, it converts the string “hello” into an array. It passes '-1' as the limit argument, so there is no limit. The “//” is passed by default to convert separate string characters into array elements.
Become a Full Stack Developer in 6 Months!
Full Stack Development-MEANexplore program
-
str_word_count() function
The str_word_count() function is another built-in function. It is not used to split the string, but it does provide 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
- $string: The first parameter that is passed to this function is the string that is to be converted into an array.
- $returnVal (optional): This parameter indicates what the function will return. This is an optional parameter and by default it is 0. It can assume three different types of values:
- 0: is also the default value. If the returnVal parameter is set to 0, the function will return the total count of the number of words in the input string.
- 1: If the returnVal parameter is set to 1, the function will return an array containing all words in the string as its elements.
- 2: If you set the returnVal parameter to 2, the function will return an array containing the key-value pairs. The key will be the index of the word and the value will contain the word itself.
- $chars (optional): This is again an optional parameter that tells the string to consider the character that is passed as a word as well.
return value
The return value of the function depends on the parameters discussed above.
The following example illustrates how the str_word_count() function works to convert a string into an array in PHP.
<?php
// define a string
$my_string = 'mundo he2llo';
// character '2' will not be considered as a word
$my_array1 = str_word_count($my_string, 1);
// print the matrix
echo "The converted array is: <br>";
print_r($my_array1); // Hello World
// the character '2' is passed as the third argument
$my_array2 = str_word_count($my_string, 1, 2);
// print the matrix
echo "<br><br>The converted array is: <br>";
print_r($my_array2); // he2llo, world
?>
In the example above, the string “he2llo world” contains a character '2' which is not considered a word by default by the str_word_count() function. So the following expression converts the string to 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, it is considered a word and included in the array.
-
Manually loop through the string
The next method on this list by which you can convert a string to an array is to manually loop through the string. You'll initialize a variable, say "i" to 0, and start a loop of "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 “i” variable.
The following example illustrates the manual approach using a for loop to convert string to array in PHP.
<?php
// define a string
$my_string = 'hello world';
// declare an empty array
$my_array = [];
// walk to string
for ($i = 0; $i < strlen($minha_string); $i++) {
if ($my_string[$i] != " ") {
$my_array[] = $my_string[$i];
}
}
// print the matrix
echo "The converted array is: <br>";
print_r($my_array); // Hello World
?>
In the example above, an empty array is initialized. The string “hello world” is traversed using a for loop and each character in the string is inserted into the array.
Free up a high-paying automation test job!
Master's Program in Test Automationexplore program
-
json_decode() function
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 byJavaScript. The JSON string usually represents objects in pairs of data values.
The syntax of the json)decode() function is:
json_decode($json, $assoc = FALSE, $ depth = 512, $options = 0)
parameters
- $json: This parameter represents the JSON string that is to be encoded into an array.
- $assoc: This parameter is of boolean data type. If true, the function will convert the encoded string into an array.
- $depth: represents the depth of the recursion that will be used to decode the string.
- $options (opcional): Inclui bitmasks de JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR.
return value
This function returns the decoded JSON string. If the depth of the encoded string is greater than the specified recursion depth limit, this function will simply return NULL.
The following example illustrates how the json_decode() function works to convert a string into an array in PHP.
<?php
// define a string
$my_string = '{"h":2, "e":5, "l":4, "l":8, "o":10}';
//convert to array
$my_array = json_decode($my_string);
// print the matrix
echo "The converted array is: <br>";
var_dump($my_array);
?>
In the example above, the string “hello” is initialized in JSON format. The json_decode() function takes this string as an argument, decodes it and converts it into an array.
-
unserialize() function
The unserialize() function is another built-in PHP function. It is the exact opposite of PHP's serialize() function. This function converts a serialized string that is passed as a parameter, back to its original form, that is, an array.
The syntax of the unserialize() function is:
unserialize($serialized_array, $options)
parameters
- $string: This parameter is the serialized string that needs to be deserialized.
- $options (optional): This is an optional parameter that represents the options that can be provided to this function.
return value
The return value can be boolean, string, integer, float or any other.
The following example illustrates how the unserialize() function works to convert a string into an array in PHP.
<?php
// define a string
$my_string = 'a:3:{i:0;s:1:"a";i:1;s:6:"sample";i:2;s:6:"string";}';
//convert to array
$my_array = unserialize($my_string);
// print the matrix
echo "The converted array is: <br>";
print_r($my_array);
?>
In the example above, 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.
Learn from the basics of JavaScript to advanced concepts of Angular, Spring Boot, Hibernate, JSPs, MVC, etc.PGP in Full Stack Web Developmenttoday!
FAQs
How to convert multiple string to array in PHP? ›
- str_split() Function.
- explode("DELIMITER", STRING)
- preg_split() Function.
- str_word_count() Function.
- Manually loop through the string.
- json_decode() Function.
- unserialize() Function.
- Using Builtin PHP Function print_r.
- Using Built-in PHP Function var_dump.
- Using PHP Inbuilt Function implode() to Convert Array to String.
- Using Foreach Loop to Print Element of an Array.
- Using the json_encode Method.
String class split(String regex) can be used to convert String to array in java. If you are working with java regular expression, you can also use Pattern class split(String regex) method.
How to break a string into an array in PHP? ›The PHP explode() function converts a string to an array. Each of the characters in the string is given an index that starts from 0. Like the built-in imlode() function, the explode function does not modify the data (string).
How do you convert a string to an array? ›We can convert a String to an array using any one of the following ways: String. split(), Pattern. split(), String[] {}, and toArray().
How to replace string with array in PHP? ›The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
Which is the correct method to convert array of strings into a list? ›- Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.
- Collections. ...
- Iteration method - Create a new list.
Strings are similar to arrays with just a few differences. Usually, the array size is fixed, while strings can have a variable number of elements. Arrays can contain any data type (char short int even other arrays) while strings are usually ASCII characters terminated with a NULL (0) character.
Which of the given method converts the array of strings into the list answer? ›Native Method
It is the simplest method to convert Java Array into a List. In this method first, we create an empty List and add all the elements of the array into the List.
You can convert any PHP data-type but resources into a string by serializing it: $string = serialize($array); And back into it's original form by unserializing it again: $array = unserialize($string);
How to split a string into an array of smaller chunks in PHP? ›
The chunk_split() function splits a string into a series of smaller parts. Note: This function does not alter the original string.
How to merge string and array in PHP? ›The join() function returns a string from the elements of an array. The join() function is an alias of the implode() function. Note: The join() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.
How to convert array to string in PHP without using function? ›PHP implode() Syntax
implode() takes in two values as parameters – the separator and the array you want to convert to a string. The separator could be any character or an empty string. It is valid as long as you specify it in quotes. If you don't pass in the separator, implode() still works.
- $string ="Raju,Anup,Irfan,Souvik";
- $arr = explode(",",$string);
- print_r($arr);
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.
How to convert string array to char array? ›- Use toCharArray() Instance Method. toCharArray() is an instance method of the String class. It returns a new character array based on the current string object. ...
- Use charAt() Instance Method. charAt() is an instance method of the String class.
To convert a PHP array to JSON data string, you can use the json_encode($value, $flags, $depth) function. The json_encode() function converts passed PHP objects into JSON formatted strings. You can control the flow of the conversion by passing optional encoding parameters to the json_encode() function.
How do you replace a value in an array in PHP? ›The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.
How to replace a string in PHP? ›- <? php.
- $string = "Hii everyone! ...
- $search = array("Hii", "We");
- $replace = array("Hello", "You");
- echo '<b>'. ...
- echo $string. ...
- $newstr = str_replace($search, $replace, $string, $count);
- echo '<b>'.
Example 3: Convert a String to ArrayList
We have used the split() method to convert the given string into an array. To learn more about splitting a string, visit Java String split(). The asList() method converts the string array into an arraylist.
Can you use array methods on strings? ›
In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays. Here is an example of an array with four elements: type Number, Boolean, String, and Object.
Which string method returns an array? ›The toString() method returns a string representing the specified array and its elements.
What are the three methods of array? ›There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.
What are the different methods to create an array? ›Create an array
This example shows three ways to create new array: first using array literal notation, then using the Array() constructor, and finally using String.prototype.split() to build the array from a string.
- Indexed arrays - Arrays with a numeric index.
- Associative arrays - Arrays with named keys.
- Multidimensional arrays - Arrays containing one or more arrays.
The String() method converts a value to a string.
What is the name of function used to convert an array into a string in PHP? ›The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order.
How do you convert an array to a string and back to an array? ›We can convert an array of numbers and an array of strings into strings using toString(). We can also convert the nested array into string using toString(). And in order to convert the string back to the array, we will use the split() method.
How to convert array of strings to numbers in PHP? ›The easiest way to convert strings to numbers in PHP is to use the (int/float/double)$variable cast, which directly converts the string to a number. You can also convert a string to a number using the intval($value, $base), floatval($value), number_format($num, $decimals) and settype($var, $type) functions.
What is array_chunk function in PHP? ›The array_chunk() function splits an array into chunks of new arrays.
How to cut spaces from string in PHP? ›
The trim() function in PHP removes whitespace or any other predefined character from both the left and right sides of a string. ltrim() and rtrim() are used to remove these whitespaces or other characters from the left and right sides of the string.
How to split a string by space in an array Java? ›Usually, words are separated by just one white space between them. In order to split it and get the array of words, just call the split() method on input String, passing a space as regular expression i.e." ", this will match a single white space and split the string accordingly.
How to merge all key values into one in single array in PHP? ›The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.
How to convert multiple object into array in PHP? ›- Type Casting Object To An Array: Type-casting, as the name suggests, we are casting the data types from one to another. ...
- Using Json Decode And Json Encode: JSON encode function returns encoded string which again needs to be decoded using JSON decode function.
You can use PHP and str_replace to replace multiple strings at once. For this, str_replace accepts arrays as input for the intial $find and $replacement parameters. $find = ['Nobody', 'remembers']; $replacement = ['Everybody', 'googles']; $string = 'Nobody remembers str_replace parameters.
How to add multiple values to array in PHP? ›Using the array_push method:
The array_push is another inbuilt function that can be used in PHP to add to arrays. This method can be used to add multiple elements to an array at once.
You create a multidimensional array using the array() construct, much like creating a regular array. The difference is that each element in the array you create is itself an array. For example: $myArray = array( array( value1 , value2 , value3 ), array( value4 , value5 , value6 ), array( value7 , value8 , value9 ) );
How to store multiple values in one array in PHP? ›To store multiple values, there are two ways of carrying out the task. One way is to assign each value to a single variable, and the other, much more efficient way, is to assign multiple values to a single variable.
How to store multiple values in array in PHP using for loop? ›Declare the $items array outside the loop and use $items[] to add items to the array: $items = array(); foreach($group_membership as $username) { $items[] = $username; } print_r($items); Hope it helps!!
How to filter multiple values in array PHP? ›The filter_var_array() function gets multiple variables and optionally filters them. This function is useful for filtering many values without calling filter_var() many times. Tip: Check the PHP Filter Reference for possible filters to use with this function.
How to replace all occurrences of a string in PHP? ›
PHP - Replacing All Occurrences using str_replace()
str_replace() replaces all occurrences of a specified string with a new string. The function takes three arguments: the search string, the replacement string, and.
To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.
How to replace all matching string in PHP? ›The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.
How to create multidimensional array in PHP dynamically? ›PHP allows a very simple way to declare a multidimensional array in PHP using the keyword 'array'. In order to declare an array inside another array, We need to add the keyword 'array' and then the elements of that array.
How to add array value in a string in PHP? ›The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
How do you assign multiple values to an array? ›The Array. concat() method takes an array or multiple values as parameters and concatenates the values into a new array.
How to create an array in PHP with syntax and small example? ›...
Example
- <? ...
- $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
- echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
A multidimensional array in PHP is a data structure that allows you to store multiple values in a single variable. As a result, arrays are an integral component of the programming community's toolkit. Arrays can hold both numeric and string values, and they can be multidimensional.
Can we store multiple data types in array in PHP? ›PHP Array. An array is a compound data type. It can store multiple values of same data type in a single variable.