Modelo

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

Converting stdClass Object to Array in PHP

Oct 19, 2024

Are you looking for a way to convert a stdClass object to an array in PHP? Look no further, as we've got you covered! stdClass is a generic empty class in PHP, and sometimes you may need to convert it to an array for easier data manipulation and processing. Here's how you can do it in just a few simple steps.

1. Using json_decode and json_encode:

You can easily convert a stdClass object to an array using the json_decode and json_encode functions in PHP. First, you need to convert the stdClass object to a JSON string using json_encode, and then decode that JSON string to an array using json_decode. Here's a sample code to demonstrate this:

```php

$stdObj = new stdClass();

$stdObj->name = 'John';

$stdObj->age = 25;

// Convert stdClass object to array

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

print_r($array);

```

2. Typecasting to array:

Another way to convert a stdClass object to an array is by typecasting it directly to an array. This can be achieved by simply casting the object to an array using (array) before the object. Here's an example:

```php

$stdObj = new stdClass();

$stdObj->name = 'Jane';

$stdObj->age = 30;

// Convert stdClass object to array

$array = (array)$stdObj;

print_r($array);

```

3. Using array functions:

You can also use array functions to convert a stdClass object to an array. You can use get_object_vars to get the properties of the object as an associative array, or you can simply iterate through the object properties and assign them to a new array. Here's an example:

```php

$stdObj = new stdClass();

$stdObj->name = 'Jake';

$stdObj->age = 35;

// Convert stdClass object to array

$array = get_object_vars($stdObj); // using get_object_vars

// Or

$newArray = [];

foreach ($stdObj as $key => $value) {

$newArray[$key] = $value;

}

print_r($newArray);

```

By using any of these methods, you can easily convert a stdClass object to an array in PHP, making it convenient for data manipulation and processing. So, next time you encounter a stdClass object and need it in array format, you know just what to do!

Recommend