Convert PHP Arrays, Integers, Objects & Variables to String

By Digamber Rawat Last updated on
Today we are going to learn how to convert arrays, integers, objects, and variables to string in PHP. We will learn to use various built-in php functions or methods to deal with string conversion.

Convert PHP Variable to String

I could convert a variable to string in PHP with my eyes shut. Jokes apart, PHP provides lots of pre-built function to deal with string conversion, we are going to use __toString() method to convert variable to string. Let us check out the below example:

<?php

class convertToString{
    public $str;

    public function __construct($str) {
        $this->str = $str;
    }

    public function __toString() {
      return (string) $this->str;
    }
}

$myObj = new convertToString('Days Gone');
echo $myObj;

?>

// Result: Days Gone

In the above example, we have used the __toString() function to convert variable to string. This function doesn’t take any argument, and it is mostly used with Objects.

Convert String to Integer in PHP

Converting string to integer or numbers is extremely simple in PHP. PHP programming language supports the type conversion, and it offers numerous functions to convert a string into numbers.

Let us have a look on some the string to number conversion php functions with an example below.

The number_format() function in PHP is used to convert a string into an integer.

<?php 
    $int = "109.126"; 
      
    echo number_format($int), "\n"; 
    echo number_format($int, 2); 
?>

// Result: 109
// Result: 109.13

In the next step, we’ll take help of primitive types to convert a string into an integer, double or float.

<?php 
  
    $number = "30061987.0915"; 
      
    // int 
    echo (int)$number, "\n"; 
    
    // double 
    echo (double)$number, "\n";
      
    // float 
    echo (float)$number, "\n"; 
?>

// Result: 30061987
// Result: 30061987.0915
// Result: 30061987.0915

Convert PHP Array to String

We are using PHP’s implode function to convert array to a string. The implode function in php takes two parameters. In the first parameter, we pass the separator. This separator is used to separate the arrays, and however, if you don’t pass any argument, then it’ll return an empty separator. In the second parameter, we pass the array object, an array which needs to be converted into a string.

<?php 
    $arrray = ['star wars', 'avengers', 'the matrix', 'ghost rider'];
    echo implode(' | ', $arrray);
?>

// star wars | avengers | the matrix | ghost rider

Convert PHP String to Arrays

Converting a string into arrays in PHP is pretty straightforward. PHP offers various methods to convert string to arrays. We will have a look at explode and str_split built-in php functions. These methods split a string and convert it into arrays, let us check out the examples below:

Using PHP’s Explode Function
Let us begin with the PHP’s explode() function, this method takes 2 argument to convert string into array. The 1st argument takes the delimiter to explode the function, and the 2nd argument takes a string. To know more about php you can visit their official site here.

<?php 
    $string = 'The Fountainhead, Dumbo, The Man Who Laughs, 7 Faces of Dr. Lao, Moulin Rouge';
    $movies_arr = explode(', ', $string);
    var_dump($movies_arr);
?>

/* Result:
array(5) {
  [0]=>
  string(16) "The Fountainhead"
  [1]=>
  string(5) "Dumbo"
  [2]=>
  string(18) "The Man Who Laughs"
  [3]=>
  string(18) "7 Faces of Dr. Lao"
  [4]=>
  string(12) "Moulin Rouge"
}
*/

Using PHP’s str_split Function to Convert String to Array
The str_split method also allows us to convert string to an array. The str_split function takes 2 arguments; in the first argument, we pass the string. In the second argument, we pass the number, and this number refers to an array element’s character length. By default, it is set to 1.

<?php 
    $string = 'Loremipsumdolorsitamet';
    $string_split = str_split($string, 3);
    var_dump($string_split);
?>

/* Result:
array(8) {
  [0]=> string(3) "Lor"
  [1]=> string(3) "emi"
  [2]=> string(3) "psu"
  [3]=> string(3) "mdo"
  [4]=> string(3) "lor"
  [5]=> string(3) "sit"
  [6]=> string(3) "ame"
  [7]=> string(1) "t"
}
*/

Convert PHP Integer to a String

Converting Integer to a string in php is not that difficult, we can use PHP’s built-in strval() function. This function is fully capable of converting string, Integer and double to a string. The important thing is to remember about this function is it shouldn’t be used with objects and arrays; if used, then this will return the type name.

The Strval Function Syntax

strval( $var )

This function takes one parameter, and that is the numerical value which needs to be converted to string. This function returns the string value as you can see in the below example.

<?php 
    $var = 124.061; 
    echo strval($var); 
?> 

// Result: 124.061

Convert String to Date/DateTime

The php offers some useful built-in functions to convert string to Date and DateTime. In this example, I’ll show you how to use strtotime(), and getDate() functions to achieve the desired results:

String to Date and DateTime Conversion using Strtotime() Example:

The strtotime() Syntax
The strtotime() in php function takes Time/Date and now (optional) parameter and returns the numerical value in seconds since Jan 1, 1970.

strtotime(argument);

The getDate() Syntax
The getDate() is useful for retrieving date/time information based on the date and time values passed into the function:

getDate(argument)
<?php 
    $time_var = strtotime("2017/02/30");
    $date_var = getDate($time_var);
    print_r ($date_var);
?> 

/* Result:
    Array(
        [seconds] => 0
        [minutes] => 0
        [hours] => 0
        [mday] => 2
        [wday] => 4
        [mon] => 3
        [year] => 2017
        [yday] => 60
        [weekday] => Thursday
        [month] => March
        [0] => 1488412800
    )
*/

Convert PHP Object to String

Now, we will covert a php object into the string using the following approach. We are taking help of __toString() and serialize() function help for converting object to string in php. We’ve already discused toString() function in the above example, let us understand what serialize() function is in php.

The serialize() method returns a string containing a byte-stream representation of any value that can be stored in PHP.
Reference: https://www.php.net/manual/en/language.oop5.serialization.php

<?php 
    class NewObject {
      public $name = 'John Wick';
    
      public function __toString() {
        return "Movie name is: {$this->name}\n";
      }
    }
    
    $OBJECT = new NewObject;
    
    echo $OBJECT;
    echo serialize($OBJECT);
?> 

/* Result: 
Movie name is: John Wick
O:9:"NewObject":1:{s:4:"name";s:9:"John Wick";} 
*/

Conclusion

In this PHP tutorial, we have learnt how to deal with strings conversion, whether it is arrays, integer, objects, or variables. I hope this tutorial will help you if you liked this tutorial, then don’t forget to share it with others. Thanks for reading, and have a good day!

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me