W3docs

How to Convert an Integer into a String with PHP

In this short guide, we will assist you to deal with one of the common issues in PHP: converting an integer into a string. Read it and follow the examples.

In this short guide, we will show you how to convert an integer into a string in PHP using the <kbd class="highlighted">strval()</kbd> function. First, let’s look at the syntax of the <kbd class="highlighted">strval()</kbd> function: <kbd class="highlighted">strval( $variable )</kbd>

Below are several examples of using the function:

php convert integer to string

<?php

$var_name = 55;

// prints the value of the variable as a string
echo strval($var_name);

?>

php convert object to string

<?php

class w3Docs
{
  public function __toString()
  {
    // returns the class name
    return __CLASS__;
  }
}

// prints the class name as a string
echo strval(new w3Docs());

?>

php convert array to string

<?php
// Illustrates the strval() function
// when an array is passed as a parameter

// Input array
$arr = [1, 2, 3, 4, 5];

// It prints the type of value
// being converted, i.e., 'Array'
echo strval($arr);

?>

Definition of the strval() Function

This is a built-in PHP function designed to convert scalar values such as integers, strings, and floats into strings. When used on arrays or objects, it does not convert their contents. Instead, it returns the string "Array" or "Object" (or triggers the __toString() method for objects).

The function accepts a single parameter: <kbd class="highlighted">$variable</kbd>, which is the value you intend to convert.