Cast an array to an object


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3.  * Note This has been tested on PHP5
  4.  * I haven't tried it on PHP4
  5.  */
  6. $arr = array(
  7. "name" => "Jamie Allison",
  8. "age" => "31"
  9. );
  10. // This is all that is required to cast an array to an object.
  11. $data = (object)$arr;
  12.  
  13.  
  14. // Next create an object manually, with the same data.
  15. // For comparison purposes below.
  16. $test = new StdClass;
  17. $test->name = "Jamie Allison";
  18. $test->age = "31";
  19.  
  20. // Print out the Results, first dump the manually created class
  21. print "Manually created StdClass" . PHP_EOL . print_r($test, true) . PHP_EOL;
  22.  
  23. // Print out the Array Cast as an object.
  24. print "Array cast to an object" . PHP_EOL . print_r($data, true) . PHP_EOL;
  25. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.