strval() Function in PHP 8.2 With Example

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

In PHP, the `strval()` function is used to convert a variable to a string. It’s particularly useful when you want to ensure that a variable is treated as a string, regardless of its original type. Here’s how `strval()` works:

<?php
string strval ( mixed $var )
?>

The `strval()` function takes one argument, `$var`, which can be of any type. It converts this variable to a string representation and returns the result.

Here’s an example demonstrating the usage of `strval()`:

<?php

// Example usage of strval()
// Define variables of different types
$intVar = 123;
$floatVar = 3.14;
$stringVar = "Hello";
$boolVar = true;
$arrayVar = array(1, 2, 3);
$objectVar = new stdClass();
$objectVar->property = "value";

// Convert variables to strings using strval()
$strInt = strval($intVar);
$strFloat = strval($floatVar);
$strString = strval($stringVar);
$strBool = strval($boolVar);
$strArray = strval($arrayVar); // Arrays are converted to the string "Array"
$strObject = strval($objectVar); // Objects are converted to the string "Object"

// Output the converted strings
echo "Converted strings:\n";
echo "Integer: $strInt\n";
echo "Float: $strFloat\n";
echo "String: $strString\n";
echo "Boolean: $strBool\n";
echo "Array: $strArray\n";
echo "Object: $strObject\n";
?>

Output:

Converted strings:
Integer: 123
Float: 3.14
String: Hello
Boolean: 1
Array: Array
Object: Object

In this example, `strval()` is used to convert variables of different types to strings. Note that boolean values are converted to “1” for `true` and an empty string for `false`. Arrays are converted to the string “Array”, and objects are converted to the string “Object”.