w3resource

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

PHP String: Exercise-4 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to check if a string contains a specific string?
Next: Write a PHP script to extract the file name from the specific string.

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.