Hello, everyone! In the previous article "Do you know how to create optional parameters in PHP? 》Introducing how to create optional parameters in PHP, interested friends can learn~
Today this article will introduce to you how to copy a given string through PHP and Output new string!
Some friends may not quite understand this title. What is copying? Output a new string again?
Don’t worry, you will know after reading the detailed description of the problem!
The specific question is "Write a PHP program to create a new string that is n (non-negative integer) times the given string, such as the string ab-> becomes ababab (can Say it is three times the original string)"?
Based on this idea, have you already figured out how to implement it?
My implementation code is given directly below:
The PHP code is as follows:
<?php function test($s, $n) { $result = ""; for ($i = 0; $i < $n; $i++) { $result = $result.$s; } return $result; } echo test("JS", 2)."<br>"; echo test("JS", 3)."<br>"; echo test("JS", 1)."<br>";
Output result:
JSJS JSJSJS JS
Done!
I believe everyone will understand it clearly after taking a look at the above code, so there is no need to introduce it in too much.
But here are a few key points to introduce to you:
1. There are two string operators in PHP. The first is the concatenation operator ("."), which returns the concatenated string of its left and right arguments. The second is the concatenation assignment operator (".="), which appends the right argument to the left argument.
2. In PHP, the for loop is used to know in advance the number of times the script needs to be run.
for (初始值; 条件; 增量) { 要执行的代码; } 参数: 初始值:主要是初始化一个变量值,用于设置一个计数器(但可以是任何在循环的开始被执行一次的代码)。 条件:循环执行的限制条件。如果为 TRUE,则循环继续。如果为 FALSE,则循环结束。 增量:主要用于递增计数器(但可以是任何在循环的结束被执行的代码)。
Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial 》~Come and learn!
The above is the detailed content of Copy the given string and output the new string through PHP. For more information, please follow other related articles on the PHP Chinese website!