Convert an Array to an Object and Vice Versa in PHP

An array is a data structure that stores one or more values in a single variable. Arrays are commonly used to store lists of items, such as the contents of a shopping cart, or the results of a database query. An object is a data structure that stores one or more values in a single variable. Objects are commonly used to store lists of items, such as the contents of a shopping cart, or the results of a database query.

In PHP, you can convert an array to an object by using the json_decode() method or by casting it as an object.

Convert an Array to an Object

//casting
$array = array('id' => 1, 'name' => 'PHP Example');
$article = (object) $array;

//create blank object and add array values to its fields
$array = ['id' => 2, 'name' => 'Kotlin Example'];
$article2 = new stdClass();
foreach ($array as $key => $value)
{
    $article2->$key = $value;
}

//use json_decode
$array = ['id' => 3, 'name' => 'Flutter Example'];
$article3 = json_decode(json_encode($array), FALSE);

Convert an Object to an Array

Similar methods can be used.

$array = (array) $object;
$array = json_decode(json_encode($object), TRUE);

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close