# Type Casting to `array` or `object`

> Section in “New and Extended Functionality › Type System” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/type-system/type-casting-to-array-or-object/>

While PHP can cast scalar values implicitly based on the current context, often casts are also performed explicitly – for instance to convert an `integer` value to a `string`. Not many developers know that PHP, in a somewhat limited way, also supports the casting of objects to arrays and back:

``` php
$obj = new stdClass;
$obj->property = 'hello world';

var_dump((array) $obj);
```

When executed, the above example will produce the following output:

    array(1) {
      'property' =>
      string(11) "hello world"
    }

The output is identical to that of `get_object_vars()` with the important difference that a cast is not limited by visibility, as the following example demonstrates:

``` php
class Sample
{
    private $property;

    public function __construct()
    {
        $this->property = 'hello world';
    }
}

$obj = new Sample;

var_dump((array) $obj);
var_dump(get_object_vars($obj));
```

    array(1) {
      '\0Sample\0property' =>
      string(11) "hello world"
    }

    array(0) {
    }

Casting an `array` to an `object` is also supported, with the hard limitation that only instances of `stdClass` are being created and only public properties can (easily) be accessed:

``` php
$data = [
    'property' => 'hello world'
];

$obj = (object) $data;
var_dump($obj->property);
```

    string(11) "hello world"

As names of properties and variables may not be of numeric type but must be a string, casting an `array` with `integer` keys did lead to inaccessible – because technically invalidly named – properties in earlier versions of PHP. The behavior has been changed and `integer` keys are now get casted to string for casts from `array` to `object` and from `string` to `integer` when objects get casted to `array`.

Given that a property named `'0'` barely makes sense and previously was inaccessible, this change of behaviour should not have any practical impact in a real-world application.

---

Previous: [The Iterable Type](https://php7explained.com/new-and-extended-functionality/type-system/the-iterable-type/index.html.md) | Next: [MySQL and Native Types](https://php7explained.com/new-and-extended-functionality/type-system/mysql-and-native-types/index.html.md)
