How to Convert Object to Array in PHP? Techniques and Examples
By Rohan Vats
Updated on Sep 10, 2025 | 15 min read | 40.88K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Sep 10, 2025 | 15 min read | 40.88K+ 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
Software Development Courses to upskill
Explore Software Development Courses for Career Progression
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.
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
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
No, typecasting is best suited for simple, flat objects and may not handle nested objects properly. If you need to convert an object with nested structures to an array, it’s better to use JSON encoding and decoding, as this method preserves the structure of nested arrays and objects. For deeply nested data, JSON encoding ensures that you capture all the levels in the conversion.
No, get_object_vars() only works for public properties of an object. It does not handle private or protected properties, meaning you will not be able to extract those with this method. If you need to access non-public properties, consider using Reflection or creating getter methods to expose those properties before conversion.
You can easily convert an array back to an object in PHP by casting the array to an object using typecasting, like this: $object = (object) $array;. This method is particularly useful when you need to work with data in an object-oriented way, such as when manipulating data within classes and methods. For nested arrays, JSON encoding/decoding is also an option to achieve the reverse conversion.
Converting an empty object to an array will result in an empty array. This happens because there are no properties to extract or convert. While this doesn’t cause any errors, it’s a good practice to check whether the object contains properties before attempting to convert it. You can use empty($object) or get_object_vars() to handle such situations more effectively.
JSON encoding in PHP can fail if your object contains non-UTF8 characters. This is because JSON only supports UTF-8 encoded data. To handle this, you should ensure that all the data in your object is UTF-8 encoded before performing the JSON encoding. You can use utf8_encode() to convert non-UTF8 strings to UTF-8 for compatibility with json_encode().
Typecasting is a fast and simple method but has limitations. It works best with simple, flat objects containing public properties. It doesn’t handle private or protected properties, and it may not work well with nested objects. For more complex data, typecasting may result in incomplete or inaccurate conversions, so using JSON encoding and decoding for nested structures is a more robust solution.
If your object contains recursive references, such as objects referring to themselves, typecasting or get_object_vars() will fail or lead to infinite loops. To handle this, consider using JSON encoding, which can serialize objects without causing recursion issues. However, you may need to manually handle such references to avoid circular references during encoding, ensuring proper serialization.
No, converting an object to an array using methods like typecasting or get_object_vars() will only extract the object’s properties, not its methods. If you need to keep track of the methods alongside the properties, you would have to manage them separately or use serialization, which includes both data and methods, although it can’t directly preserve methods in an array.
While JSON encoding/decoding is versatile, it isn't suitable for all objects when learning how to convert object to array in PHP. For instance, it doesn’t work well with resources (like file handles or database connections) or objects with non-UTF8 characters. Always check the compatibility of your object before using JSON methods, especially when dealing with special data types or large resources.
get_object_vars() only works with public properties, so when learning how to convert object to array in PHP with private or protected properties, it won’t include those properties. If you need to include non-public properties in the array, you can either use Reflection to access them or create getter methods in the class to expose those properties before conversion.
408 articles published
Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...
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