View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Convert Object to Array in PHP? Techniques and Examples

By Rohan Vats

Updated on Jun 30, 2025 | 15 min read | 40.34K+ views

Share:

Did you know? PHP 8.1 now supports Fibers, a feature that lets you pause and resume code execution for true multitasking! 

This update makes tasks like handling non-blocking I/O and managing event loops more efficient than ever, no external libraries needed!

To convert an object to an array in PHP, you can use three methods: typecasting, JSON encoding/decoding, and get_object_vars(). In real-life applications, like processing API responses or database data, you often need to transform objects into arrays for easier manipulation. 

However, choosing the right method can be tricky depending on the complexity of the data.

This article will guide you on how to convert object to array in PHP, helping you handle data transformations with ease and efficiency, no matter the situation.

Improve your coding skills with upGrad’s online software engineering courses. Specialize in cybersecurity, full-stack development, and much more. Take the next step in your learning journey!

How to Convert Object to Array in PHP? Three Essential Techniques

Let's say you’re working with a PHP-based e-commerce platform like Shopify, where customer data is retrieved via an API in object format. You need to manipulate this data, maybe to display it on a dashboard or process it for analysis, but it's much easier to work with arrays. This is where converting an object to an array becomes essential. 

Before getting into the techniques, make sure you’re comfortable with basic PHP syntax and object handling, as these techniques build on fundamental knowledge. 

Working with object-to-array conversion in PHP isn’t just about understanding the techniques. You need hands-on practice to apply your skills effectively, handle edge cases, and select the most suitable method for your data. Here are three programs that can help you:

Below are the three essential techniques on how to convert object to array in PHP, each suited for different scenarios.

1. Typecasting

Typecasting is one of the simplest and most straightforward techniques when learning how to convert object to array in PHP. It’s quick and ideal for situations where you’re working with basic, flat objects.  

For example, imagine you’re working on a PHP-based CRM system for a small business. The system receives customer data as an object from a third-party API, and the customer’s details are relatively simple, such as their name, contact information, and status. 

In this case, typecasting allows you to quickly convert the object to an array, making it easier to display the data in a table or pass it to another function without the overhead of more complex methods.

Let’s look at an example where we simulate receiving customer data in an object format and need to convert it into an array for processing.

Step 1: Create an Object

We’ll first create a basic object that represents customer data, such as their name, age, and email. 

$customer = (object) [    "name" => "Ajay Sharma",    "age" => 28,    "email" => "ajay.sharma@example.com"];

Explanation:

  • Line 1: We create an object $customer with three properties: "name", "age", and "email". The object is cast from an associative array using (object).

Step 2: Cast the Object to an Array

Next, we will typecast the object to an array using the (array) syntax. 

$customerArray = (array) $customer;

Explanation:

  • Line 2: This line typecasts the $customer object into an array and stores it in the variable $customerArray. 

Step 3: Display the Result

Finally, we use the print_r() function to display the resulting array structure. 

print_r($customerArray);

Explanation:

  • Line 3: print_r() is used to print the resulting array in a human-readable format.

Expected Output:

After running the above code, the output will look like this: 

Array
(
    [name] => Ajay Sharma
    [age] => 28
    [email] => ajay.sharma@example.com
)

Explanation:

  • The output shows that the object has been successfully converted into an array. The object properties (name, age, and email) are now accessible as array keys with corresponding values. 

While typecasting is quick and simple, it has limitations, especially when dealing with more complex or deeply nested objects.  

If you’re working with deeply nested objects, typecasting won’t suffice. In such cases, consider using JSON encoding and decoding to ensure all nested elements are handled correctly.

Also Read: Type Casting in Java: What Is Casting in Java and How to Use It Effectively in 2025

Best Practices and Tips

  • Check Object Validity First
    Always verify that the data you're typecasting is indeed an object. Use is_object($object) to prevent errors from non-object data.
  • Avoid Typecasting Nested Objects
    Typecasting won't handle deeply nested objects well. For nested structures, consider using JSON encoding/decoding instead.
  • Use Typecasting on Simple, Flat Objects Only
    Typecasting is best for objects with straightforward properties. For more complex objects, choose a method that handles multi-layered data, like json_encode().
  • Maintain Consistent Property Names
    Ensure property names are simple and consistent. Typecasting works best when object properties follow clear naming conventions and are easily accessible as array keys.

Also Read: The Ultimate Guide to Interfaces in PHP: Definition, Implementation, and Best Practices for 2025

2. JSON Encoding and Decoding

When working with more complex objects, especially those with nested data, typecasting alone won’t suffice. This is where JSON encoding and decoding come into play. This technique is particularly useful when you need to handle multi-layered data, such as when working with data from a RESTful API or when exporting data to external systems. 

When integrating with an external service like Twitter’s API, the data you receive may contain nested objects. For example, the API response might return a user object, which includes nested objects like the user's posts, followers, and media. To work with such data, you’ll need to convert the object to an array that properly handles all of the nested structures.

Let’s walk through how to use JSON encoding and decoding to convert an object to an array.

Step 1: Create an Object with Nested Data

We'll simulate receiving a user object from an API that contains nested data about the user’s details and recent posts. 

$user = (object) [    "username" => "jia_kapoor",    "details" => [        "age" => 30,        "location" => "New Delhi"    ],
    "posts" => [        ["title" => "First Post", "date" => "2021-01-01"],
        ["title" => "Second Post", "date" => "2021-06-15"]
    ]
];

Explanation:

  • Line 1: We create an object $user with three properties: "username", "details", and "posts". The "details" and "posts" are nested arrays within the object.

Step 2: JSON Encode the Object and Decode It to an Array

Now, we will encode the object into a JSON string and then decode it back to an array. 

$jsonString = json_encode($user);
$userArray = json_decode($jsonString, true);

Explanation:

  • Line 2: json_encode($user) converts the $user object into a JSON string.
  • Line 3: json_decode($jsonString, true) converts the JSON string back into an associative array. The true parameter ensures that the result is an array, not an object.

Step 3: Display the Result

Finally, use print_r() to see the array structure: 

print_r($userArray);

Explanation:

  • Line 4: print_r() is used to print the resulting array in a readable format.

Expected Output: 

Array
(
    [username] => jia_kapoor
    [details] => Array
        (
            [age] => 30
            [location] => New Delhi
        )
    [posts] => Array
        (
            [0] => Array
                (
                    [title] => First Post
                    [date] => 2021-01-01
                )
            [1] => Array
                (
                    [title] => Second Post
                    [date] => 2021-06-15
                )
        )
)

Explanation:
The output shows that the object has been converted into an array, with nested data preserved. The "details" and "posts" properties are arrays, making the structure more manipulable.

Also Read: Foreach Loop in PHP: A Guide to Functions, Use Cases, and Best Practices for 2025

Best Practices and Tips

  1. Check for Errors During JSON Encoding
    Always check the result of json_encode() to ensure the object was successfully converted into a JSON string. Use json_last_error() to catch any errors.
  2. Handle Non-UTF8 Characters
    Be mindful when working with non-UTF8 characters. JSON encoding may not handle these well, so ensure your data is UTF-8 encoded.
  3. Use json_decode() With Care
    Remember that json_decode() can handle large datasets, but if the JSON string is too large, it may impact performance. Use pagination or chunked data loading for handling big responses.
  4. Avoid Encoding Large Objects Unnecessarily
    If the object is small and flat, typecasting may still be the better choice. Save JSON encoding for objects that are too complex for simple typecasting.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

If you're finding it tough to break down complex problems efficiently, check out upGrad’s Data Structures & Algorithms free course to strengthen your foundation and start solving challenges with ease. Start today!

3. get_object_vars()

The get_object_vars() function is another effective method for converting an object to an array in PHP. Unlike typecasting, which transforms the object as a whole, get_object_vars() allows you to extract the public properties of an object into an associative array. 

This technique is especially useful when you need access to only the object's properties and not the full object structure.

When you're working with a PHP-based content management system (CMS) or managing user profiles, the need arises to access only the public properties of an object, such as the user’s name, email, and subscription status. 

For example, a system may have a User class with various properties and methods, but you may only need to manipulate the public properties. get_object_vars() helps extract these properties into an array, making it easy to work with them.

Let’s walk through an example where we extract the public properties of a User object using get_object_vars().

Step 1: Create an Object with Public Properties

We’ll first create a User object with some public properties. 

$user = new stdClass();
$user->name = "Samanta Das";
$user->email = "samanta.das@example.com";
$user->status = "active";

Explanation:

  • Line 1: We create an empty stdClass object and assign values to its public properties: name, email, and status.

Step 2: Use get_object_vars() to Convert the Object to an Array

Next, we use get_object_vars() to convert the object’s public properties into an associative array. 

$userArray = get_object_vars($user);

Explanation:

  • Line 2: get_object_vars($user) extracts the public properties of the $user object and stores them as an associative array in the variable $userArray.

Step 3: Display the Result

Finally, display the resulting array using print_r(): 

print_r($userArray);

Explanation:

  • Line 3: print_r() prints the array in a human-readable format, allowing us to verify the conversion.

Expected Output: 

Array
(
    [name] => Samanta Das 
    [email] => samanta.das@example.com
    [status] => active
)

Explanation: 

The output shows the public properties of the $user object as keys in the resulting array, with their corresponding values.

Best Practices and Tips

  1. Ensure Properties Are Public
    get_object_vars() only works on public properties. If you need private or protected properties, you'll need to make them public or use other techniques, such as Reflection or custom getter methods.
  2. Use in Simple Data Structures
    This method works best for objects with a relatively simple, flat structure. If you need to convert deeply nested objects, consider using JSON encoding instead.
  3. Check Object Type Before Usage
    Always verify that the data is an object before using get_object_vars() to avoid errors. Use is_object($object) for this purpose.
  4. Custom Getter Methods for More Control
    If you want fine-grained control over which properties are included in the array, consider implementing a custom getter method in your class to expose only the necessary properties.

Looking to advance your PHP data handling skills? Check out upGrad’s Executive Program in Generative AI for Business Leaders, which will equip you with the skills needed to lead in AI-driven industries while levelling up your backend skills. Start today!

Try implementing these techniques in real-life projects, such as processing API responses or working with user data. Now that you've learned the key techniques on how to convert object to array in PHP, it's important to be aware of potential edge cases and common errors.  

Edge Cases and Common Errors to Avoid

 

When learning how to convert object to array in PHP, it's easy to focus on the basic techniques. However, real-life applications often involve unexpected scenarios that can cause errors or result in data loss. 

Below are some of the most common edge cases and mistakes to avoid:

1. Handling Private and Protected Properties

Pitfall: Typecasting and get_object_vars() do not handle private or protected properties of objects.

Solution: If you need to access these properties, you’ll need to either make them public or use reflection to retrieve them. Alternatively, implement custom getter methods to expose them for conversion.

Example: 

class User {
    private $name;
    private $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }

    public function getName() {
        return $this->name;
    }
}

$user = new User("Ajay", "ajay@example.com");
$userArray = get_object_vars($user); // Won't work for private properties

Fix: Use a getter method or Reflection: 

$reflection = new ReflectionClass($user);
$properties = $reflection->getProperties();

2. Converting Nested Objects

Pitfall: Typecasting doesn’t handle nested objects properly, often resulting in them being lost or not properly converted.

Solution: Use JSON encoding/decoding for handling nested objects, as it preserves the structure.

Example: 

$object = (object) [    "name" => "Bani",    "address" => (object) [        "street" => "123 Main St",        "city" => "New Delhi"    ]
];
$array = (array) $object;  // Nested object not handled properly

Fix: 

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

3. Handling Non-UTF8 Characters

Pitfall: JSON encoding may fail if your data contains non-UTF8 characters (like special symbols or non-English alphabets).

Solution: Ensure that the data is UTF-8 encoded before using JSON functions. Use utf8_encode() if necessary.

Example: 

$object = (object) ["name" => "Shreya"];
$jsonString = json_encode($object); // May fail if encoding is not UTF-8

Fix: 

$object->name = utf8_encode($object->name);
$jsonString = json_encode($object); // Now works fine

4. Data Loss with Typecasting for Non-Standard Objects

Pitfall: Typecasting may result in data loss for non-standard objects or objects with custom methods or properties that aren’t straightforward to convert.

Solution: Consider using reflection or a custom method to handle these objects, or serialize the object if necessary.

Example: 

class Product {
    public $name;
    public $price;
    private $discount;

    public function __construct($name, $price, $discount) {
        $this->name = $name;
        $this->price = $price;
        $this->discount = $discount;
    }

    public function getDiscount() {
        return $this->discount;
    }
}

$product = new Product("Laptop", 1000, 200);
$array = (array) $product;  // Private properties won't be included

Fix: Use Reflection or custom getters to handle the conversion: 

$productArray = get_object_vars($product); // Still won't work for private properties

5. Misleading Results with Typecasting Non-Associative Objects

Pitfall: Typecasting can behave unpredictably when converting non-associative objects or objects with unusual structures.

Solution: Ensure that the object structure is compatible with associative arrays. If the object is a standard class with numeric keys, the conversion might not give expected results.

Example: 

$arrayObject = new ArrayObject([1, 2, 3]);
$array = (array) $arrayObject; // Might not work as expected

Fix: Instead of typecasting, use get_object_vars() or loop through the object properties manually.

6. Handling Null or Undefined Objects

Pitfall: Converting null or undefined objects can cause errors or produce unexpected results.

Solution: Always check if the object is valid before performing the conversion.

Example: 

$object = null;
$array = (array) $object; // Results in an empty array, but can cause confusion

Fix: Always validate if the object exists: 

if (is_object($object)) {
    $array = (array) $object;
} else {
    // Handle the error
}

Also Read: Top 12 PHP Developer Skills: Key Technologies & Frameworks for 2025

As you continue exploring PHP, dive into advanced topics like serialization and Reflection for complex objects. You can also focus on data manipulation in APIs with nested structures. These will give you greater control and flexibility in your projects.

How Can upGrad Help You in Your Java Development Career?

Techniques like typecasting, JSON encoding/decoding, and using get_object_vars() to convert objects to arrays in PHP are fundamental for handling data efficiently. However, as you handle more complex data, challenges may arise, such as dealing with nested structures or private properties.

To overcome these hurdles, practice regularly and explore edge cases. This will help you learn how to convert an object to an array in PHP and ensure you're well-prepared for real-life scenarios.

For further growth in PHP, upGrad’s courses in web development and backend programming can help you learn complex data structures and concurrency.

In addition to the courses mentioned above, here are some more free courses that can help you advance your skills: 

Curious which courses can help you advance in PHP development? upGrad’s personalized career guidance can help you explore the right learning path based on your goals. You can also visit your nearest upGrad center and start hands-on training today!  

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Reference:
https://php.watch/versions/8.1/fibers

Frequently Asked Questions (FAQs)

1. Can I use typecasting for objects with nested data structures?

2. Does get_object_vars() work for private or protected properties in an object?

3. How can I convert an array back into an object in PHP?

4. What happens if I try to convert an empty object to an array?

5. Can I convert objects with non-UTF8 characters using JSON encoding/decoding?

6. What are the limitations of using typecasting to convert objects to arrays?

7. What should I do if my object contains recursive references?

8. Can I convert an object to an array in PHP while maintaining its methods?

9. Can I use JSON encoding/decoding for all objects when learning how to convert object to array in PHP?

10. Why does get_object_vars() fail with non-public properties when learning how to convert object to array in PHP?

Rohan Vats

408 articles published

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

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months