1

When you get some database record using PHP extensions of 3rd party libraries you know that some of them return an array and some other return object, during web development I have to cast such object to array and vice versa, or at least remember that foo is array and boo is object and using proper syntax to access the record attributes. This is annoying and I think perhaps there was a syntax sugar that make it a litter easier, isn't it?

I want access to attributes of a recode regardless of it structure. because we know to following structure have same syntactical power.

$foo = ['a'=>'b','x'=>'y'];

$foo = new stdClass();
$foo->a='b';
$foo->x='y';

In javscript: foo={a:'b',x:'y'}; and then x= foo['a']; or x= foo.a; if this is possible in JS why not in PHP?

Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • This quesion is quite similar, and might have some solutions: http://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array – lethal-guitar Jan 21 '13 at 14:01

2 Answers2

0

You can use (object)$array_name to typecast (change type of variable to object) and vise versa (array)$obj_name

    //Array To Object Example
    $person = array (
       'firstname' => 'Richard',
       'lastname' => 'Castera'
    );
     
    $p = (object) $person;
    echo $p->firstname; // Will print 'Richard'

    //Object to Array Example
    $array = (array) $object;
0

There is no easy way to do this I can write you a code that uses PHP ArrayObject Class and converts every object / array to PHP ArrayObject (http://php.net/manual/en/class.arrayobject.php) but this will be more complex then typecasting