PHP Function Reference

PHP strval() Function



The PHP strval() function returns the string value of a variable.

Note: This function performs no formatting on the returned value. To format a numeric value as a string, sprintf() or number_format() can be used.

Note: This function can not be used on arrays or on objects that do not implement the __toString() method. It can be used with variable of any scalar type or an object that implements the __toString() method.

Syntax

strval(variable)

Parameters

variable Required. Specify the variable that is being converted to a string.

Return Value

Returns string value of the variable.

Example: strval() example

The example below shows the usage of strval() function.

<?php
echo strval("Hello")."\n";
echo strval(10)."\n";
echo strval(10.5)."\n";
echo strval(1e3)."\n";
echo strval("123Hello")."\n";
?>

The output of the above code will be:

Hello
10
10.5
1000
123Hello

Example: using on objects

The strval() function can be used on object of a class which implements the __toString() method. Consider the example below:

<?php
class person {
  private $name;
  private $age;

  //class constructor
  function __construct($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }

  //implementing __toString() method
  public function __toString() {
    return $this->name." is ".$this->age." years old.\n";     
  }   
};

//creating objects of class person
$p1 = new person('John', 25);
$p2 = new person('Marry', 24);

//using strval() function on objects
echo strval($p1);
echo strval($p2);
?>

The output of the above code will be:

John is 25 years old.
Marry is 24 years old.

❮ PHP Variable Handling Reference