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:
For working professionals
For fresh graduates
More
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.
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.
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:
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:
Step 3: Display the Result
Finally, we use the print_r() function to display the resulting array structure.
print_r($customerArray);
Explanation:
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:
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
Also Read: The Ultimate Guide to Interfaces in PHP: Definition, Implementation, and Best Practices for 2025
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:
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:
Step 3: Display the Result
Finally, use print_r() to see the array structure:
print_r($userArray);
Explanation:
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
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!
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:
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:
Step 3: Display the Result
Finally, display the resulting array using print_r():
print_r($userArray);
Explanation:
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
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.
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.
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
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
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
Top Resources