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);