Home > Article > Backend Development > How to concatenate two variables into a string array in php
In PHP, concatenating variables can be implemented using the .
operator. The same operation is done to concatenate two variables into a string array. The specific implementation method is as follows:
.
operator to splice variables: $var1 = "Hello"; $var2 = "World"; $string = $var1 . " " . $var2; // 将变量拼接为字符串 "Hello World"
explode()
function is converted to an array: $var1 = "Hello"; $var2 = "World"; $string = $var1 . " " . $var2; // 拼接变量为字符串 "Hello World" $array = explode(" ", $string); // 使用空格分隔符将字符串转换为数组 print_r($array); // 输出结果为["Hello", "World"]
Note: Using the explode()
function requires specifying a delimiter, so that the string will be cut according to the delimiter into array items.
In addition to using the explode()
function, we can also use the array's []
operator to add variable values to the array:
$var1 = "Hello"; $var2 = "World"; $array = [$var1, $var2]; // 直接使用数组添加变量值 print_r($array); // 输出结果为["Hello", "World"]
Or simpler writing:
$var1 = "Hello"; $var2 = "World"; $array = [$var1, " ", $var2]; // 直接使用数组添加变量值和分隔符 print_r($array); // 输出结果为["Hello", " ", "World"]
In this way, the two variables can be spliced into a string array. According to actual needs, you can choose to use the explode()
function or the []
operator of the array to implement it.
The above is the detailed content of How to concatenate two variables into a string array in php. For more information, please follow other related articles on the PHP Chinese website!