Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to prepend a string in PHP ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

We have given two strings and the task is to prepend a string str1 with another string str2 in PHP. There is no specific function to prepend a string in PHP. In order to do this task, we have the following operators in PHP:

Method 1: Using Concatenation Operator(“.”): The Concatenation operator is used to prepend a string str1 with another string str2 by concatenation of str1 and str2.

Syntax:

$x . $y

Example :

PHP




<?php
// PHP program to prepend a string 
  
  
// Function to prepend a string 
function prepend_string ($str1, $str2){
      
    // Using concatenation operator (.)
    $res = $str1 . $str2;
      
    // Returning the result 
    return $res;
    }
  
// Given string
$str1 = "Geeksforgeeks"
$str2 = "Example"
  
// Function Call
$str = prepend_string ($str1, $str2); 
  
// Printing the result
echo $str
?>


Output

GeeksforgeeksExample

Method 2: Using Concatenation assignment operator (“.=”): The Concatenation assignment operator is used to prepend a string str1 with another string str2 by appending the str2 to the str1.

Syntax:

$x .= $y

Example :

PHP




<?php
// PHP program to prepend a string 
  
// Function to prepend a string 
function prepend_string ($str1, $str2) {
      
    // Using Concatenation assignment
    // operator (.=)
    $str1 .= $str2;
      
    // Returning the result 
    return $str1;
}
  
// Given string
$str1 = "Geeksforgeeks"
$str2 = "Example"
  
// Function call
$str = prepend_string ($str1, $str2); 
  
// Printing the result
echo $str
?>


Output

GeeksforgeeksExample

My Personal Notes arrow_drop_up
Last Updated : 31 May, 2020
Like Article
Save Article
Similar Reads
Related Tutorials