echo strval(34)."<br>"; //34
echo strval(12.34)."<br>"; // 12.34
echo strval(12.340)."<br>"; // 12.34
echo strval(.34)."<br>"; // 0.34
echo strval(0.34)."<br>"; // 0.34
echo strval(-0.34)."<br>"; // -0.34
echo strval('plus2net')."<br>";// plus2net
From any type of data ( variable ) we can get string output. This can be used to convert any numeric data to string. $my_num=strval(12345678);
$sum=0;
for($i=0; $i<strlen($my_num); $i++){
if(($i % 2) ==0){
$sum=$sum + $my_num[$i];
}
}
print($sum)
Output is 16
The *strval()* function can also be used to convert boolean values to strings, returning either '1' for true or an empty string for false.
$true_val = strval(true);
$false_val = strval(false);
echo "True: $true_val, False: $false_val";
This will output:
True: 1, False:
When converting null values to strings, *strval()* returns an empty string.
$null_val = strval(null);
echo "Null: '$null_val'";
This will output:
Null: ''
While *strval()* cannot directly convert arrays, we can use *implode()* in conjunction with it to join array elements into a string.
$arr = [1, 2, 3];
$str = strval(implode(", ", $arr));
echo $str;
This will output:
1, 2, 3
In scenarios where user input needs to be safely cast to a string to prevent errors in concatenation or display:
$user_input = 45.67; // Could be any data type
$safe_input = strval($user_input);
echo "User input: " . $safe_input;
This ensures that any variable, regardless of its type, is safely converted to a string.
Objects need to implement the *__toString()* method to be converted into strings using *strval()*.
class MyClass {
public function __toString() {
return "Object as string";
}
}
$obj = new MyClass();
echo strval($obj);
This will output:
Object as string