How to Copy String in PHP ?
Last Updated :
27 Feb, 2024
Copying a string is a basic operation that all the programming languages offer. In this article, we will explore different approaches to copying a string in PHP, including using the assignment operator, the strval()
function, the substr()
function and by implementing the strcpy()
function.
Copy String using Assignment Operator
The simplest way to copy a string in PHP is by using the assignment operator (=
). This operator copies the value from the right-hand side to the left-hand side.
Example: Illustration of copying a string in PHP using the assignment operator.
PHP
<?php
$str = "Hello, World!" ;
$copiedStr = $str ;
echo $copiedStr ;
?>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Copy String using strval()
Function
The strval()
function can be used to convert a variable to a string. This function can also be used to copy a string. This approach is particularly useful when the original variable is not strictly a string (e.g., a number or an object) but needs to be copied as a string.
Example: Illustration of copying a string in PHP using the strval() function.
PHP
<?php
$str = "Hello, World!" ;
$copiedStr = strval ( $str );
echo $copiedStr ;
?>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Copy String using substr()
Function
The substr()
function can be used to extract a substring from a string. In this case, we’re starting from the beginning (offset 0) and extracting the entire string, effectively creating a copy.
Example: Illustration of copying a string in PHP using the substr() function.
PHP
<?php
$str = "Hello, World!" ;
$copiedStr = substr ( $str , 0);
echo $copiedStr ;
?>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Implementing a strcpy()
Function
While PHP does not have a native strcpy()
function like C, you can implement a similar function using string assignment. This custom strcpy()
function takes two parameters: a reference to the destination string and the source string.
Example: Illustration of copying a string in PHP by implementing a strcpy() function.
PHP
<?php
function strcpy(& $destination , $source ) {
$destination = $source ;
}
$str = "Hello, World!" ;
strcpy( $copiedStr , $str );
echo $copiedStr ;
?>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...