Casting arrays as objects (and vice-versa) in PHP

I just learned that it's possible to cast an associative array as an object in PHP.

It works the other way, too—an object can be cast as an array.

This is especially useful when working with the results of database queries. A lot of codebases seem unsure whether to treat database rows as arrays, or as objects. In these environments, it's likely that you'll get one type as the return value from a particular method, but need to pass the other type as an argument to a second method.

So it's nice to have a simple and language-native way to convert between the two. Some simple demo code:

<?php
 
// create an array
$array = array(
	'prop1' => 'value1',
	'prop2' => 'value2'
);
 
// cast it to an object
$object = (object) $array;
echo 'The value of the property prop1 is: ' . $object->prop1 . '<br />';
echo 'The value of the property prop2 is: ' . $object->prop2 . '<br />';
 
// cast it back to an array
$array2 = (array) $object;
echo 'The value for the key prop1 is: ' . $array2['prop1'] . '<br />';
echo 'The value for the key prop2 is: ' . $array2['prop2'] . '<br />';
 
?>

Comments

No comments yet.

Leave a Reply

(will not be published)
(optional)

What My Clients Say

Travis has worked on several projects for us and we have an ongoing relationship which we value. He has excellent technical skills and communication skills. He is highly effective in taking a project from concept to completion. In addition, he is able to communicate with business professionals effectively.

—Clarence Johnson
FSI Holding Corp.