Page 1 of 1

PHP - Convert stdClass object to Array

Posted: 02 May 2015, 06:49
by PloMar
I have the following object in php:

Code: Select all

$ob = new stdClass;
$ob->name = 'some-name';
$ob->email = 'email-address';
$ob->site = 'https://coursesweb.net/';
How can I covert it to an array, so I can use: $array['property']?

PHP - Convert stdClass object to Array

Posted: 02 May 2015, 06:52
by Admin
Hi,
Just use the: (array) $objectName construction.

Code: Select all

$ob = new stdClass;
$ob->name = 'some-name';
$ob->email = 'email-address';
$ob->site = 'https://coursesweb.net/';

$arr = (array) $ob;
echo $arr['name']; 
- And viceversa, with: (object) $arrayName you can convert an Array to an Object.

Code: Select all

$arr = [
  'name'=> 'some-name',
  'email'=> 'email-address',
  'site'=> 'https://coursesweb.net/'
];

$ob = (object) $arr;
echo $ob->name;