PHP - Convert stdClass object to Array

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts: 48

PHP - Convert stdClass object to Array

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']?

Admin Posts: 805
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;