CONVERT A STRING TO A NUMBER IN PHP

PHP is an open-source language that is used for server-side development & scripting. It is widely known & 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 tệp tin 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 & the advantages of achieving this.

Bạn đang xem: Convert a string to a number in php

Why vì You Need to lớn Convert a String khổng lồ an Array in PHP?

There are many cases when an array is considered more suitable over a string. For instance, you can convert the passwords entered as đầu vào in a website application into an array before storing them in the database. This provides more security và ease of access to the data. Arrays can help you implement better data organization & faster operations. When you convert a string into an array, it makes data manipulation convenient. Being a powerful scripting language, PHP provides various in-built methods to lớn convert a string khổng lồ an array. This article explains several approaches lớn achieve this task.

Following is the complete list of methods that can be used in PHP to lớn convert a string to an array.

str_split() Functionexplode("DELIMITER", STRING)preg_split() Functionstr_word_count() FunctionManually loop through the stringjson_decode() Functionunserialize() Function

Different Methods to lớn Convert String to lớn Array in PHP

There are various approaches, including in-built functions và manual approaches that are used lớn convert string to lớn array in PHP. 

str_split() Function

The first method in this các mục 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 và 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$initial_string (mandatory): The first parameter you pass to lớn this function is the string that has lớn be converted into an array.

$splitting_length (optional): The second parameter is an integer that represents how long the parts of the strings 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 that contains the pieces of the original string. If the length that is passed lớn 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 lớn convert string lớn array in PHP.

");

// 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 khổng lồ an array. The following expression passes the string to lớn this method without passing the length argument.

$my_array1 = str_split($my_string); 

By default, if you bởi not pass the length delimiter, it takes it as 1. So, it converts separate elements of the string into array elements. & 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);

explode("DELIMITER", STRING);

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 lớn be passed as an argument lớn 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.

Xem thêm: http hoadon quangnam vnpt index php

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 lớn split the string whenever it detects the separator & stores that substring in the array.$initial_name: The second parameter that is passed lớn this function is the string that has to lớn be converted into an array.$no_of_elements (optional): This is the last and an optional parameter that is passed khổng lồ this function. This parameter represents the number of strings in which it should split the original string. This number can be positive, negative, or zero.Positive: If the passed integer is positive, then the array will store this many numbers of elements. If you separate the string into more than N number of pieces regarding the delimiter, the first N-1 elements remain the same, and the rest of the elements combine to form a single element.Zero: If the passed integer is 0, then the array will contain the whole string as a single element.Negative: If the passed integer is negative then the last N elements of the array will be cut off và it will return the remaining elements. 

Return Value

The 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 lớn convert string to array in PHP.

";

print_r($my_array1); // red, green, blue 

?>

*
 

In the above example, you are converting a string containing three colors separated by a comma lớn an array. The comma “,” is passed to the explode() function as a delimiter to convert the string into array elements.

preg_split() Function

The preg_split() is also an in-built PHP function that is used to lớn convert a string into an array by splitting it into smaller substrings. Just lượt thích 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$pattern: The pattern is a regular expression that determines what character is used as a separator lớn split the string.$string: The second parameter that is passed to this function is the string that has to be converted into an array.$limit (optional): The limit indicates the total number of substrings in which it will split the string. If all the separators appear before the limit ends, the (limit-1) elements remain the same & the rest of the elements combine to khung the last element. If the limit is 0, then, it will return the whole string as one single element. However, it is an optional parameter. If not mentioned, it will consider the limit as -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 on which the final array will be returned. These options or conditions are:PREG_SPLIT_NO_EMPTY: This flag type is used lớn remove the empty string and the non-empty strings will be returned.PREG_SPLIT_DELIM_CAPTURE: This flag type is used khổng lồ get the delimiter in the resulting array as well. If this flag is used, then the expression within the parenthesis will also be captured as an array element.PREG_SPLIT_OFFSET_CAPTURE: This flag type makes the function return a pair as an array element. The first part of the pair will be the substring & 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 khổng lồ the function.

The following example illustrates the working of the preg_split() function to lớn convert string to array in PHP.

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 lớn convert separate characters of the string into array elements. 

str_word_count() Function

The str_word_count() function is another in-built function. It is not used lớn split the string, but it gives information about the string, such as the number of characters in the string, & 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 lớn this function is the string that has 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 take three different kinds of values:0: It is also the value by default. If the returnVal parameter is set to lớn 0, then 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, then the function will return an array containing all the words of the string as its elements.2: If you phối if the returnVal parameter lớn 2, then 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 parameter to lớn as a word as well. Return Value

The 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 lớn array in PHP.

";

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 "The converted array is: ";

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 và ‘2’ is omitted.

$my_array1 = str_word_count($my_string, 1);

When you pass the character ‘2’ as the third argument khổng lồ the str_count_world() function, then it is considered as a word and included in the array.