Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

How to Convert Object to Array in PHP

Updated on 05 December, 2024

39.24K+ views
6 min read

Managing data structures is at the heart of programming. Whether you're organizing API responses or structuring databases, knowing how to convert an object to an array or transform an array into an object is a game-changer. These techniques save you time and make your code more efficient and easier to debug.

You’ve probably faced challenges with messy data or cumbersome conversions at some point. That’s exactly why this guide is here. By understanding these methods in PHP and JavaScript, you’ll be equipped to streamline data handling and avoid common pitfalls. Think of this as your go-to resource for better coding practices.

Get ready to explore clear examples, step-by-step explanations, and practical tips to make your coding experience smoother and more productive. Let’s begin!

How to Convert Object to Array in PHP?

Understanding how to convert an object to array PHP can save you a lot of trouble, especially when dealing with data transformation in APIs or dynamic applications. 

PHP provides several straightforward methods for this conversion, each tailored for different scenarios. Whether you need a quick fix or a scalable approach, you'll find a method that suits your needs.

Discover three powerful techniques to achieve this conversion below.

Typecasting Object to Array PHP

When it comes to a fast and simple way to convert object to array in PHP, typecasting is your go-to method. With minimal syntax, you can achieve the transformation directly. But does it have limitations? Sure, it’s quick, but it’s not always suited for complex objects.

To begin, use this simple syntax to cast an object into an array without additional complexities.

$array = (array) $object;

The following program shows how to convert object to array using typecasting.

<?php
// Creating an object
$object = (object) [
    "name" => "John Doe",
    "age" => 30,
    "email" => "john.doe@example.com"
];

// Converting object to array
$array = (array) $object;

// Displaying the array
print_r($array);
?>

This output confirms how typecasting transforms the object into a structured array.

Array
(
    [name] => John Doe
    [age] => 30
    [email] => john.doe@example.com
)

Explanation of the Program

The object $object is created with three properties: nameage, and email. Using (array) before the object instantly converts it into an associative array. The print_r() function reveals the array structure in a readable format. This method is ideal for small objects but may not handle nested structures well.

Also Read: Interface in PHP | PHP OOPs Interfaces

Typecasting is easy, but you might need more flexibility. The following technique covers this gap.

JSON Encoding and Decoding

JSON encoding and decoding allow you to handle nested objects and complex data structures. This method is a lifesaver when working with Rest APIs or exporting data to external systems. The trick is to convert the object into a JSON string and then decode it back as an array.

Check out how you can use this method effectively.

Here’s the syntax you’ll need for converting objects to arrays using JSON encoding and decoding.

$jsonString = json_encode($object);
$array = json_decode($jsonString, true);

The following program walks you through the steps of encoding and decoding to achieve the conversion.

<?php
// Creating an object
$object = (object) [
    "name" => "Jane Doe",
    "details" => [
        "age" => 25,
        "profession" => "Engineer"
    ]
];

// Converting object to array
$jsonString = json_encode($object);
$array = json_decode($jsonString, true);

// Displaying the array
print_r($array);
?>

Check the result of using JSON encoding and decoding to convert object to array.

Array
(
    [name] => Jane Doe
    [details] => Array
        (
            [age] => 25
            [profession] => Engineer
        )
)

Explanation of the Program

The json_encode() function converts the object into a JSON string, capturing its structure, including nested arrays or objects. The json_decode() function transforms this string into an array, preserving nested elements. Adding true as the second parameter ensures the result is an array, not another object.

This method shines when you handle multi-layered data but requires additional steps. The next approach flips the process.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

 

How to Create an Object from an Array in PHP

The reverse process—transforming an array into an object—can be just as crucial. Imagine receiving data from a database or API in an array format but needing it as an object for cleaner property access. PHP gives you multiple options to achieve this.

Follow these approaches to convert an array into an object effectively. Typecasting works for simple cases where you need quick conversions.

<?php
// Creating an array
$array = [
    "title" => "Developer",
    "experience" => 5
];

// Converting array to object
$object = (object) $array;

// Displaying the object
print_r($object);
?>

The output below showcases the structure of the converted object.

stdClass Object
(
    [title] => Developer
    [experience] => 5
)

The following approach illustrates converting nested arrays into objects using json_decode.

<?php
// Creating an array
$array = [
    "company" => "Tech Corp",
    "employees" => [
        "John" => "Manager",
        "Emily" => "Engineer"
    ]
];

// Converting array to object
$jsonString = json_encode($array);
$object = json_decode($jsonString);

// Displaying the object
print_r($object);
?>

Here’s how the resulting object appears when you decode nested data structures.

stdClass Object
(
    [company] => Tech Corp
    [employees] => stdClass Object
        (
            [John] => Manager
            [Emily] => Engineer
        )
)

Converting arrays to objects is particularly helpful in the following cases. 

  • Integrating APIs that prefer objects over arrays.
  • Simplifying property access with -> instead of associative array syntax.
  • Maintaining consistent data formats across functions and classes.

Now that you’ve mastered these conversions in PHP, it’s time to shift gears. You’ll next explore how similar operations work in JavaScript.

How Can upGrad Help You Ace Your Programming Career

To thrive in the tech industry, you need to stay ahead by constantly learning and upgrading your skills. With upGrad, you get access to one of the top online learning platforms, trusted by over 10 million learners worldwide. 

You can choose from 200+ courses designed to match industry needs, and with 1,400+ hiring partners, you’ll also find opportunities to secure your dream job. If you're wondering about the programming courses available for learners in India, the following options will match your goals perfectly.

To make your journey smoother, you also get access to free one-on-one expert career counselling sessions. This personalized guidance will help you clarify your goals, match your skills with the right opportunities, and build a roadmap for long-term success.

Unlock your potential with our Popular Software Engineering Courses, crafted to equip you with essential skills like coding, problem-solving, and system design. Dive into real-world projects, gain mentorship from industry experts, and prepare for top-tier roles in tech!

Elevate your career with in-demand software development skills, including coding, API integration, and software testing. Gain expertise through practical projects and become the go-to professional in the tech world!

Stay updated with the latest trends and insights in software development by exploring our popular articles. From programming tips to emerging technologies, find expert knowledge all in one place!

Frequently Asked Questions (FAQs)

1. How to Convert a List of Objects to an Array of Objects in PHP?

Use json_decode(json_encode($list), true) to convert a list of objects into an array of objects in PHP.

2. How Do You Set an Object in an Array in PHP?

Assign the object to an array index: $array[] = $object; to add it to the array.

3. How Can You Check If a Variable Is an Object in PHP?

Use is_object($variable) to determine if a variable is an object in PHP.

4. What Function Converts an Object's Properties to an Associative Array?

get_object_vars($object) returns an associative array of an object's properties.

5. How to Convert a Multidimensional Array to an Object in PHP?

Use json_decode(json_encode($array)) to convert a multidimensional array into an object.

6. How Do You Access Object Properties After Conversion to an Array?

Access properties using associative array syntax: $array['property'].

7. Can Private and Protected Properties Be Converted to an Array?

Yes, but they may require special handling to access after conversion.

8. How to Convert an Array of Objects to a JSON String in PHP?

Use json_encode($arrayOfObjects) to convert an array of objects to a JSON string.

9. How Do You Convert a JSON String to an Object in PHP?

Use json_decode($jsonString) to convert a JSON string into an object.

10. What Is the Difference Between Typecasting and JSON Methods for Conversion?

Typecasting is faster for simple objects; JSON methods handle complex, nested structures effectively.

11. How Do You Handle Nested Objects When Converting to an Array?

Use recursive functions or JSON methods like json_decode(json_encode($object), true) for nested structures.

RELATED PROGRAMS