w3resource

PHP String Exercises: Convert the value of a PHP variable to string


4. Convert Variable to String

Write a PHP script to convert the value of a PHP variable to string.

Visual Presentation:

PHP String Exercises: Convert the value of a PHP variable to string

Sample Solution:

PHP Code:

<?php
$x =  20;            // Assigns the integer value 20 to the variable $x
$str1 = (string)$x;  // Converts the integer $x to a string and assigns it to $str1
// Check whether $x and $str1 are equal or not
if ($x === $str1)    // Compares $x and $str1 for both value and type
{
  echo "They are the same"."\n"; // Prints if $x and $str1 are identical
}
else
{
  echo "They are not same"."\n"; // Prints if $x and $str1 are not identical
}
?>

Output:

They are not same

Explanation:

In the above PHP code, '$x' is an integer with a value of 20, which is then converted to a string and stored in '$str1'. The code then compares '$x' and '$str1' to see if they are identical in both value and type. If they are identical, it prints "They are the same"; otherwise, it prints "They are not same".

Flowchart :

Flowchart: Convert the value of a PHP variable to string

For more Practice: Solve these Related Problems:

  • Write a PHP function that accepts a variable of any type and returns its string representation using type juggling and explicit casting.
  • Write a PHP script to convert an array, object, or number to a string and then concatenate it with a predefined message.
  • Write a PHP program that demonstrates converting a boolean or null value to a string and outputs the result.
  • Write a PHP script to serialize a complex variable into a string and then unserialize it back to verify integrity.

Go to:


PREV : Check if String Contains Another.
NEXT : Extract Filename from Path.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.