Mastering PHP: Convert Any Variable to a String with strval
This guide explains how PHP's built‑in strval function converts integers, floats, booleans, arrays, and objects to strings, demonstrates each conversion with sample code, and highlights important caveats such as arrays and objects returning "Array" or "Object" and how to use json_encode for deeper serialization.
PHP provides the built‑in strval function to convert a given value to its string representation. If the argument is already a string, it is returned unchanged; otherwise, the function casts the value based on its type.
Below are practical examples that illustrate how strval handles different data types:
<?php
// Convert an integer to a string
$number = 123;
$str_number = strval($number);
echo gettype($str_number); // string
echo $str_number; // 123
// Convert a float to a string
$float = 3.14;
$str_float = strval($float);
echo gettype($str_float); // string
echo $str_float; // 3.14
// Convert a boolean to a string
$bool = true;
$str_bool = strval($bool);
echo gettype($str_bool); // string
echo $str_bool; // 1
// Convert an array to a string
$array = [1, 2, 3];
$str_array = strval($array);
echo gettype($str_array); // string
echo $str_array; // Array
// Convert an object to a string
class Person {
public $name = "John";
public $age = 30;
}
$person = new Person();
$str_person = strval($person);
echo gettype($str_person); // string
echo $str_person; // Object
?>The examples show that strval successfully casts integers, floats, and booleans to their textual forms. When applied to arrays or objects, the function returns the type name ("Array" or "Object") rather than the actual contents.
If you need the concrete values of an array or object, use a different approach such as json_encode, which serializes the data structure into a JSON string.
In everyday PHP development, whenever a variable must be represented as a string—whether for output, concatenation, or logging— strval offers a concise and reliable solution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
