PHP Convert An Array To An Object Example

Today, We want to share with you PHP Convert An Array To An Object Example.In this post we will show you php array to object stdclass, hear for convert multidimensional array to object php we will give you demo and example for implement.In this post, we will learn about PHP : Convert or Cast Array to Object & Object to Array with an example.

PHP Convert An Array To An Object Example

There are the Following The simple About PHP Convert An Array To An Object Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop convert associative array to object php, so the PHP Object to Array conversion for this example is following below.

Example :1 php array to object stdclass

The Array Example

 [
      'Mobile',
  'Laptop'
 ]
];

print Array

array:1 [▼
  "items" => array:2 [▼
    0 => "Mobile"
    1 => "Laptop"
  ]
]

Convert to an Object

Step 1 – Encode This data to a string

$object = json_encode($array);
var_dump($object);

output – var_dump

"{"items":["Mobile","Laptop"]}"

Step 2 – Decode This Data to an Object

$object = json_decode(json_encode($array));
var_dump($object);

var_dump Output

stdClass Object ( [items] => Array ( [0] => Mobile [1] => Laptop ) )

Alternative Way

$object = (object)$array;

var_dump($object);
//stdClass Object ( [items] => Array ( [0] => Mobile [1] => Laptop ) )

assuming PHP $var is a multidimensional array Convert

$obj = json_decode (json_encode ($my_array), FALSE);
var_dump($obj);

Example 2: PHP Object to Array conversion

Input

<?php

class GetMember
{
    public $member = 'memberData';
}

$GetMember = new GetMember();

$arrayGetMember = (array) $GetMember;

var_dump($arrayGetMember);

Output

array(1) {
    ["member"]=> string(8) "memberData"
}

Private and Protected properties

<?php

class GetMember
{
    public $member = 'memberData';
    protected $company = 'CompanyData';
    private $tab = 'teamData';
}

$GetMember = new GetMember();

$arrayGetMember = (array) $GetMember;

var_dump($arrayGetMember);

Output

array(3) {
    ["member"]=> string(8) "memberData"
    ["*company"]=> string(8) "CompanyData"
    ["GetMembertab"]=> string(8) "teamData"
}

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Convert An Array To An Object Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment