In PHP programming, we often need to use the same string to be repeated multiple times, such as output delimiters, string padding, etc. At this time, you can use the str_repeat function in PHP to repeat the string.
The str_repeat function is a built-in function used to repeat a string several times. Its syntax is as follows:
string str_repeat ( string $input , int $multiplier )
Among them, $input is the string to be repeated, and $multiplier is repeated frequency. The return value is the repeated string.
Let’s look at some examples:
Example 1:
$str = "PHP"; echo str_repeat($str, 3);
The output result is:
PHPPHPPHP
Example 2:
$str = "*"; echo str_repeat($str, 10);
The output result is:
**********
Example 3:
$str = "Hello World! "; echo str_repeat($str, 5);
The output result is:
Hello World! Hello World! Hello World! Hello World! Hello World!
As can be seen from the above example, the str_repeat function is very concise, clear and very practical. . Using it can greatly reduce the amount of code and time cost when we program.
It should be noted that the $multiplier parameter cannot be a negative number, otherwise a Warning warning will be thrown and an empty string will be returned. When the value of $multiplier is 0, the function will directly return an empty string. In addition, the $input parameter can also receive an empty string, in which case an empty string will be returned directly.
The above is an introduction to how to use the str_repeat function in PHP to repeat a string. Hope this helps PHP beginners!
The above is the detailed content of How to repeat a string using str_repeat function in PHP. For more information, please follow other related articles on the PHP Chinese website!