Home > Backend Development > PHP Tutorial > How to repeat a string using str_repeat function in PHP

How to repeat a string using str_repeat function in PHP

王林
Release: 2023-06-26 12:24:01
Original
1710 people have browsed it

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 )
Copy after login

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);
Copy after login

The output result is:

PHPPHPPHP
Copy after login

Example 2:

$str = "*";
echo str_repeat($str, 10);
Copy after login

The output result is:

**********
Copy after login

Example 3:

$str = "Hello World! ";
echo str_repeat($str, 5);
Copy after login

The output result is:

Hello World! Hello World! Hello World! Hello World! Hello World!
Copy after login

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!

Related labels:
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