Home > Backend Development > PHP Problem > How to concatenate two variables into a string array in php

How to concatenate two variables into a string array in php

PHPz
Release: 2023-04-23 10:02:29
Original
1462 people have browsed it

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:

  1. Use the . operator to splice variables:
$var1 = "Hello";
$var2 = "World";
$string = $var1 . " " . $var2; // 将变量拼接为字符串 "Hello World"
Copy after login
  1. Use the spliced ​​string explode() function is converted to an array:
$var1 = "Hello";
$var2 = "World";
$string = $var1 . " " . $var2; // 拼接变量为字符串 "Hello World"
$array = explode(" ", $string); // 使用空格分隔符将字符串转换为数组
print_r($array); // 输出结果为["Hello", "World"]
Copy after login

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"]
Copy after login

Or simpler writing:

$var1 = "Hello";
$var2 = "World";
$array = [$var1, " ", $var2]; // 直接使用数组添加变量值和分隔符
print_r($array); // 输出结果为["Hello", " ", "World"]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template