PHP str_repeat() Tutorial

beginner
9 min

PHP str_repeat() Tutorial

Welcome to CodeYourCraft's PHP str_repeat() tutorial! In this lesson, we'll explore the str_repeat() function, learn how to use it, and understand its practical applications. By the end, you'll be able to repeat strings in your PHP projects with confidence! 🎯

What is str_repeat()?

The str_repeat() function in PHP is used to repeat a given string a specified number of times. It's a handy tool for creating repeated patterns or filling data with the same value. πŸ’‘

Syntax

The basic syntax of the str_repeat() function is:

php
string str_repeat ( string $string , int $repeat )
  • $string: The string you want to repeat.
  • $repeat: The number of times you want to repeat the string.

Example

Let's create a simple example to better understand the str_repeat() function.

php
<?php $str = "Hello"; $repetitions = 3; $repeated_string = str_repeat($str, $repetitions); echo $repeated_string; ?> Output: "HelloHelloHello" πŸ“ ## Practical Applications Here are some practical uses of the `str_repeat()` function: - Filling a form with placeholder text - Creating repeated background patterns - Generating repeated HTML elements - Creating hashed passwords (combined with `sha1()` or `md5()`) ## Pro Tip: Remember, the `str_repeat()` function will return an empty string if the `$repeat` value is 0 or less than 1. πŸ’‘ ---
Quick Quiz
Question 1 of 1

What does the PHP `str_repeat()` function do?


Now that you've learned the basics of the PHP str_repeat() function, it's time to put it to use in your projects! πŸ’ͺ

Stay tuned for more PHP tutorials on CodeYourCraft! πŸ“

Here's another example demonstrating the use of str_repeat() in creating a simple password hasher:

php
<?php function generate_hashed_password($password, $salt) { $hashed_password = str_repeat($salt, 10) . sha1($password . $salt); return $hashed_password; } $password = "mysecretpassword"; $salt = "SuperSecretSalt"; $hashed_password = generate_hashed_password($password, $salt); echo $hashed_password; ?> Output: A hashed password that is unique for each run. πŸ“