Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP str_repeat() Function

PHP str_repeat() Function

The str_repeat() function is a built-in function in PHP and is used to create a new string by repeating a given string fixed number of times. It takes a string and an integer as arguments and returns a new string which is generated by repeating the string passed as an argument by the number of times defined by the integer passed as an argument to this function.

Syntax:

string str_repeat ( $string, $no_of_times )

Parameters: This function accepts two parameters and both of them are mandatory to be passed.

  1. $string: This parameter represents the string to be repeated
  2. $no_of_times: This parameter represents a number denoting the number of times the parameter $string is to be repeated. This parameter should be greater than or equals to zero.

Return Value: This function returns a new string made up by repeating the given string $string given number of times. If the parameter $no_of_times passed to the function is equals to 0, then the function returns an empty string.

Examples:

Input : $str = \'GeeksForGeeks\';
        print_r(str_repeat($str, 2));
Output :GeeksForGeeksGeeksForGeeks

Input : $str = \' Run\';
        print_r(str_repeat($str, 7));
Output : Run Run Run Run Run Run Run

Below programs illustrate the str_repeat() function in PHP:
Program – 1:




<?php
  
// Input string
$str = 'GeeksForGeeks';
  
// Repeated string
print_r(str_repeat($str, 2));
  
?>


Output:

GeeksForGeeksGeeksForGeeks

Program – 2:




<?php
  
// Input string 
$str = ' Run';
  
// Repeated string
print_r(str_repeat($str, 7));
  
?>


Output:

 Run Run Run Run Run Run Run

Reference:
http://php.net/manual/en/function.str-repeat.php

RELATED ARTICLES

Most Popular

Recent Comments