How to prepend a string in PHP ?
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
function prepend_string ( $str1 , $str2 ){
$res = $str1 . $str2 ;
return $res ;
}
$str1 = "Geeksforgeeks" ;
$str2 = "Example" ;
$str = prepend_string ( $str1 , $str2 );
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
function prepend_string ( $str1 , $str2 ) {
$str1 .= $str2 ;
return $str1 ;
}
$str1 = "Geeksforgeeks" ;
$str2 = "Example" ;
$str = prepend_string ( $str1 , $str2 );
echo $str ;
?>
|
Output
GeeksforgeeksExample
Last Updated :
31 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...