strval() to get string from a variable

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.

The return value is string.

Application using strval()

Find the sum of every 2nd digit of any integer.
$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

Example 2: Converting Boolean Values to Strings

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: 

Example 3: Converting Null Values to Strings

When converting null values to strings, *strval()* returns an empty string.

$null_val = strval(null);
echo "Null: '$null_val'";

This will output:

Null: ''

Example 4: Converting Arrays to Strings (Indirectly)

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

Use Case: Safely Casting User Input

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.

Example 5: Using strval() with Objects

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

Declaring variables Cookies to store Infomation Getting Type of Variable var_dump() empty()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer