Skip to main content

Convert an object to an array and vice-versa in PHP.

<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('object_to_array')) {
  /**
   * Convert an stdClass object to a multi-dimensional array.
   * 
   * @param object $obj
   * @return array
   */
  function object_to_array($obj) {
    if (is_object($obj)) {
      $obj = get_object_vars($obj);
    }
    
    if (is_array($obj)) {
      return array_map(__FUNCTION__, $obj);
    } else {
      return $obj;
    }
  }
}

if (!function_exists('array_to_object')) {
  /**
   * Convert a multi-dimensional array to an object (recursive).
   *
   * @param $arr array
   * @return stdClass
   */
  function array_to_object($arr) {
    if (is_array($arr)) {
      return (object) array_map(__FUNCTION__, $arr);
    } else {
      return $arr;
    }
  }
}