Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to object in PHP?

How can I convert an array like this to an object?

[128] => Array     (         [status] => "Figure A.  Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."     )  [129] => Array     (         [status] => "The other day at work, I had some spare time"     ) 
like image 488
streetparade Avatar asked Dec 08 '09 18:12

streetparade


People also ask

How do you object an array in PHP?

Converting an object to an array with typecasting technique: php class bag { public function __construct( $item1, $item2, $item3){ $this->item1 = $item1; $this->item2 =$item2; $this->item3 = $item3; } } $myBag = new bag("Books", "Ball", "Pens"); echo "Before conversion :".

What is the easiest way to convert an array to an object?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.

How do you object in PHP?

To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.


2 Answers

In the simplest case, it's probably sufficient to "cast" the array as an object:

$object = (object) $array; 

Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:

$object = new stdClass(); foreach ($array as $key => $value) {     $object->$key = $value; } 

As Edson Medina pointed out, a really clean solution is to use the built-in json_ functions:

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

This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.

Warning! (thanks to Ultra for the comment):

json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL

like image 64
jlb Avatar answered Oct 12 '22 03:10

jlb


you can simply use type casting to convert an array to object.

// *convert array to object* Array([id]=> 321313[username]=>shahbaz) $object = (object) $array_name;  //now it is converted to object and you can access it. echo $object->username; 
like image 34
Shahbaz Avatar answered Oct 12 '22 04:10

Shahbaz