Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Convert stdClass Object to Array in PHP

Oct 17, 2024

Hey guys, today we're going to talk about how to convert a stdClass object to an array in PHP. This is a common task when working with APIs or JSON data. Let's jump right into it!

Step 1: Create your stdClass object

First, you need to have a stdClass object that you want to convert to an array. You can create a stdClass object using the `stdClass` keyword like this:

```php

$stdObj = new stdClass;

$stdObj->name = 'John';

$stdObj->age = 25;

$stdObj->city = 'New York';

```

Step 2: Use json_decode and json_encode

Now, you can easily convert this stdClass object to an array using the `json_decode` and `json_encode` functions. Here's how you can do it:

```php

$array = json_decode(json_encode($stdObj), true);

```

The `json_encode` function will encode the stdClass object into a JSON string, and then the `json_decode` function with the second parameter as `true` will decode the JSON string into an associative array.

Step 3: Access the array

Now, you can easily access the elements of the array just like you would with any other array in PHP. For example, you can echo the name and age from the array like this:

```php

echo 'Name: ' . $array['name'];

echo 'Age: ' . $array['age'];

```

And that's it! You have successfully converted a stdClass object to an array in PHP. This is a quick and easy way to work with stdClass objects and manipulate their data as arrays.

I hope you found this tutorial helpful. If you have any questions or other PHP topics you'd like me to cover, let me know in the comments below. Don't forget to like and share this video. Thanks for watching!

Recommend