Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconHow to Convert Object to Array in PHP [With Example]

How to Convert Object to Array in PHP [With Example]

Last updated:
21st Sep, 2022
Views
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
How to Convert Object to Array in PHP [With Example]

Navigating through the world of PHP development presents a myriad of tasks where understanding data manipulation becomes crucial. One such common challenge that often puzzles beginners and even some seasoned developers is how to convert object to Array in PHP? Through my experience, I’ve realized the importance of mastering this skill, as it bridges the gap between object-oriented and array-based programming paradigms in PHP. This article aims to demystify this process, offering a straightforward guide that leverages PHP’s capabilities to efficiently convert objects into arrays.

Whether you’re dealing with JSON data, API responses, or just need a more accessible way to handle your data, mastering this conversion is crucial. We will explore the basics of Object-Oriented Programming (OOP) in PHP and delve into practical examples to illustrate the conversion process. By sharing my first-hand experience and technical insights, I hope to empower aspiring PHP developers to enhance their coding toolkit and embrace the versatility PHP offers. 

Check out our free courses to get an edge over the competition.

Object-Oriented Programming (OOP) in PHP

One of the key aspects of PHP is object-oriented programming where the data is treated as an object, and software is implemented on it. This is one of the simplified approaches of advanced PHP. Object-oriented programming is achievable with PHP where objects have rules defined by a PHP program they are running in. These rules are called the classes. They are very important if you are looking to convert object to array in PHP. 

Ads of upGrad blog

Check out upGrad’s Advanced Certification in Blockchain

Some OOP Concepts

Before getting into how objects are converted into arrays, let’s first learn about some important terms related to object-oriented programming in PHP.

Class

Classes are the data types defined by a programmer. It includes local function and local data. A class can serve as a template for making multiple instances of the same class of objects.

Object

An individual instance of the data structure is defined by a class. Many objects belonging to a class can be made after defining a class once. Objects are also called as instances.

Explore our Popular Software Engineering Courses

Check out upGrad’s Java Bootcamp

Example Defining a Class and its Objects

class Jobs {

   // Members of class Jobs

}

// Creating three objects of Jobs

$software = new Jobs;

$pharmaceutical = new Jobs;

$finance = new Jobs;

Array

An array, in PHP, is a special kind of variable that holds more than one value at a time.

In-Demand Software Development Skills

Defining an Array

In PHP, the array is defined with the array function ‘array()’.

Example:

<?php

$numbers = array(“One”, “Two”, “Three”);

echo count($numbers);

?>

Read: 15 Exciting PHP Project Ideas & Topics For Beginners

Object to Array PHP

There are mainly two methods by which an object is converted into an array in PHP:

1. By typecasting object to array PHP

2. Using the JSON Decode and Encode Method

Read our Popular Articles related to Software Development

Let’s have a look at both in detail:

1. Typecasting Object to Array PHP

Typecasting is a method where one data type variable is utilized into a different data type, and it is simply the exact conversion of a data type. It is also one of the most used methods of converting an object to array in PHP.

In PHP, an object can be converted to an array with the typecasting rules of PHP.

Syntax:

$myArray = (array) $myObj;

Program:

<?php

   class shop {

      public function __inventory( $product1, $product2, $product3){

         $this->product1 = $product1;

         $this->product2 =$product2;

         $this->product3 = $product3;

      }

   }

   $myShop= new shop(“Grocery”, “Cosmetic”, “Grain”);

   echo “Before conversion :”.'</br>’;

   var_dump($myShop);

   $myShopArray = (array)$myShop;

   echo “After conversion :”.'</br>’;

   var_dump($myShopArray);

?>

Output:

 Before conversion:

object(shop)#1 (3) { [“product1″]=> string(5) ” Grocery ” [“product2″]=> string(4) ” Cosmetic ” [“product3″]=> string(4) ” Grain ” }

After conversion:

array(3) { [“product1″]=> string(5) ” Grocery ” [“product2″]=> string(4) ” Cosmetic ” [“product3″]=> string(4) ” Grain ” }

 Explanation of the program:

In the above program, a class “shop” is created. In the ‘shop’ class, the function ‘inventory()’ is created. The function inventory() will be executed when an object is created.

The constructor will receive arguments provided when the object is created with a new keyword. In the first var_dump() expression, the object is printed. The second time, the object is type casted into an array using the type-casting procedure.

2. Using the JSON Decode and Encode Method

Object to array PHP is also done with the JSON decode and encode method. In this method, the json_encode() function returns a JSON encoded string for a given value. The json_decode() function accepts the JSON encoded string and converts it into a PHP array. This is a very popular method used to convert object to array PHP.

Syntax:

$myArray = json_decode(json_encode($object), true);

Program:

<?php

   class employee {

      public function __company($firstname, $lastname) {

         $this->firstname = $firstname;

         $this->lastname = $lastname;

      }

   }

   $myObj = new employee(“Carly”, “Jones”);

   echo “Before conversion:”.'</br>’;

   var_dump($myObj);

   $myArray = json_decode(json_encode($myObj), true);

   echo “After conversion:”.'</br>’;

   var_dump($myArray);

?>

Output:

Before conversion:

object(student)#1 (2) { [“firstname”]=> string(4) ” Carly ” [“lastname”]=> string(6) ” Jones ” }

After conversion:

array(2) { [“firstname”]=> string(4) ” Carly ” [“lastname”]=> string(6) ” Jones ” }

Explanation of the program:

In the program above, a class with the name ‘employee’ is created. In that class, a function ‘company()’ is declared which will be executed during the creation of the object.

The constructor receives the arguments given when creating the object using a new keyword. In the first var_dump() expression, the object is printed and in the second, the object is converted into an array using json_decode and json_encode technique.

How to create an Object from Array in PHP

PHP object to array and how to convert object to array PHP have been covered. We will now examine how to build an object from an array. You are free to use any of the distinct examples mentioned above for PHP object to array to do this in order to meet the demands of your own code.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Method 1 – 

Use json_decode and json_encode Method

The json decode() and json encode() methods in PHP may be used to create an object from an array, similar to changing an object to an array PHP. The array is first produced, and then it is transformed into an object. The array is transformed into an object using – 

$object = json_decode (json_encode ($array))

The output is then printed out using –

function var_dump(variable of the object)

For example – 

<?php

//Arrays of types of cars

$carArray = [

‘cars’ => [‘Benz’,  ‘BMW’,  ‘AUDI’]

];

//Convert array into an object

$object = json_decode(json_encode($carArray));

//Print array as an object using

var_dump($object);

?>

Output – 

object(stdClass)#1 (1) {

[“cars”] =>

array (3)  {

[0] =>

string(4)  “Benz”

[1] =>

string(3)  “BMW”

[2] =>

string(4) “AUDI”

}

Convert Associative Array into Object 

In this instance, an associative array is transformed into an object using the formula –

$object = (object) $array 

Finally, we use this method to print the output 

var_dump(variable of an object)

For Example 

<?php

//Arrays of types of cars

$carArray = array(

‘cars’ => [‘Benz’ , ‘BMW’ , ‘Audi’],

‘parts’ => [‘tyre’, ‘mirror’, ‘footmat’]

);

//Convert array into an object

$object = (object) $carArray;

//Print array as an object, all elements under $carArray

var_dump($object);

//Print array as an object, only elements within ‘parts’ in $carArray Array

var_dump($object ->parts)

?>

Output – 

object(stdClass)# (2) {

[“cars”] =>

array(3) {

[0] =>

string(4) “Benz”

[1] =>

string(3) “BMW”

[2] =>

string(4) “AUDI”

}

[“parts”] =>

array(3)  {

[0]=>

string(4) “tyre”

[1] =>

string(6) “mirror”

[2] =>

string(7) “footmat”

}

}

array(3)  {

[0]=>

string(4) “tyre”

[1] =>

string(6) “mirror”

[2] =>

string(7) “footmat”

}

Convert a Multidimensional Array to an Object

With this technique, a multidimensional array is transformed into an object by applying the formula 

$object = (object) $array 

Finally, we use this method to print out the variable 

var_dump (variable of an object)

For example – 

<?php

//Arrays of types of cars

$schoolArray = array(

“One” => Array(“student” =>’John Doe’),

“Two” => Array(“subject” => “Introduction to Computer Science’),

“Three” => Array(“grade” = ‘84’)

);

//Convert array into an object

$ibject = (object) $schoolArray;

//Print array as an object, all elements under $schoolArray

var_dump($object);

?>

Output – 

object(stdClass) #1 (3) {

[“one”]=>

array(1) {

[“student”]=>

string(8) “John Doe”

}

[“two”]=>

array(1) {

[“subject”] =>

string (32) “Introduction to Computer Science”

}

[“three”]=>

array(1) {

[“grade”] =>

string(2) “84”

}

}

array(1)  {

[“student”]=>

string(8)  “John Doe”

}

Convert Array to Object With Foreach Loop 

When you wish to turn an array into an object, you may apply the same technique as mentioned for PHP convert object to array, but this time try to use a foreach loop. Additionally, the array is turned into an object using the syntax 

$object = (object) $array

Finally, we use this method to print the variable 

var_dump(variable of an object)

For example 

<?php

//Array of school-related things

$schoolArray = array(

“one” => Array(“student” = > ‘John Doe’),

“two” => Array(“subject” => ‘Introduction to Computer Science’)

“three” => Array(“grade” => ‘84’)

);

$object = new stdClass();

//Using foreach loop

foreach ($schoolArray as $keys => $value)    {

$object -> {$keys} = $value;

}

//Print array as an object, all elements under $schoolArray

var_dump($object);

?>

Output 

object(stdClass)#1 (3) {

[“one”]=>

array(1)  {

[“student”]=>

string(8) “John Doe”

}

[“two”]=>

array(1)  {

[“subject”]=>

string(32) “Introduction to Computer Science”

}

[“three”]=>

array(1)  {

[“grade”]=>

string(2) “84”

}

}

Also Read: 15 Interesting PHP Projects on Github For Beginners

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Ads of upGrad blog

 

Conclusion

In this article, we have introduced one of the most prominent topics of PHP. As a programmer, you will be dealing with every aspect of the language and have to work on some of the most complicated PHP concepts when moving to the advanced level. Hope this article highlighting the methods for converting an object to array in PHP will prove out to be a reference point for you.

upGrad brings programming with PHP and a lot more with upGrad’s PG Diploma in Software Development Specialisation in Full Stack Development. A program to make you emerge as a full stack developer and learning to build some of the awesome applications. It is an extensive 12-months program that includes working on live projects and assignments and also training 15 programming languages and tools. Along with it, it has all-time career support with mock interviews and job assistance.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are the applications of PHP?

PHP stands for HyperText Preprocessor. PHP is used to handle forms, connect to the database, send and retrieve data to and from the database, etc. PHP is simple, easy to learn, and integrates with other applications. It is used for making requests like GET, POST, PUT, DELETE, UPDATE, etc. It can be used to create APIs (Application Programming Interface). It also ensures the secure transfer of data by encrypting it. Also, session management can also be done in PHP using cookies and session objects. PHP is platform-independent. Some of the organizations that use PHP are Wikipedia, Slack, WordPress, etc.

2Why would one want to convert an object to an array in PHP?

An array is a data structure that helps to store values. Each value in the array can be accessed through an index. An object is a compound data type that stores the values or properties of an element. Objects exhibit the properties of a class. Arrays provide a lot of functions that can be applied to the data. It helps in easier manipulation and easier extraction of useful data stored in the array. They are lightweight and simple. Hence, while writing code for some applications we might want to convert objects to an array.

3What are the various principles of object-oriented programming?

Data Abstraction, Encapsulation, Inheritance, and Polymorphism are the principles of object-oriented programming. Data Abstraction deals with showing the user only what is necessary and hiding the unnecessary and trivial details. Encapsulation is a means of binding the common functionalities and objects with the same properties or attributes together in the form of a class. Inheritance is the process of gaining access to some features and properties of the parent class. It helps in the reusability of code and ensures modularity. Polymorphism means “many forms”. It's of 2 types: compile time and run time. Here, one function can have multiple implementations. All these features help us in writing clean code.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31545
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46899
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901298
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
51980
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909119
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34719
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902367
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26128
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4327
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon