Open In App

How to Copy String in PHP ?

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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!";
// copying a string using
// assignment operator
$copiedStr = $str;
  
echo $copiedStr;
  
?>


Output

Hello, World!

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!";
// copying a string using
// strval() function
$copiedStr = strval($str);
  
echo $copiedStr;
  
?>


Output

Hello, World!

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!";
// copying a string using
// substr() function
$copiedStr = substr($str, 0);
  
echo $copiedStr;
  
?>


Output

Hello, World!

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
// strcpy() function
function strcpy(&$destination, $source) {
    $destination = $source;
}
  
$str = "Hello, World!";
strcpy($copiedStr, $str);
echo $copiedStr;
  
?>


Output

Hello, World!

Time Complexity: O(1)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads