How to convert object or array to string in php?

In this post, by using the implode() function in php, we can convert all object or array elements into a string. This function returns the string.

1. Code:

 <?php 
 class Point2D {
  var $x, $y;
  var $label;
  
  function getPoint()
  {
     return array("x" => $this->x, "y" => $this->y, "label" => $this->label);
  }
   function Point2D($x, $y)
  {
     $this->x = $x;
     $this->y = $y;
  }
}

function convertObjectOrArrayToString($object, $space = "", $key = "", &$resultValue = ""){
    if (!is_object($object)) {
        if (is_array($object)) {
            $object = implode(",", $object);
        }
        $resultValue .= " - <b>$object</b><br/>";
    } else {
        if (isset($key) || trim($key) != '') {
            $resultValue .= ":<br/>";
        }
        $space .= "--";
        foreach (get_object_vars($object) as $key => $value) {
            if ((isset($key) || trim($key) != '') && isset($value)) {
                $resultValue .= $space . " " . $key . convertObjectOrArrayToString($value, $space, $key);
            }
        }
    }
    return $resultValue;
}

$str = array(1, 3, 4, 2, 22);
$str = convertObjectOrArrayToString($str);
echo($str);
echo "<br/>";

$p1 = new Point2D(1.233, 3.445);
echo convertObjectOrArrayToString($p1);
?> 

2. Example:

Input:

array(1, 3, 4, 2, 22);
$p1 = new Point2D(1.233, 3.445);

Output:

- 1,3,4,2,22
:
-- x - 1.233
-- y - 3.445

3. Download this Example from Github

Download here