Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Type Casting Object To An Array
1.2.
Using Json Decode And Json Encode
2.
Arrays in PHP
2.1.
Numeric Array or Indexed Array
2.2.
Associative Array
2.3.
Multidimensional Arrays
3.
Object-Oriented Programming (OOP) in PHP
3.1.
Explanation of the Code
4.
Frequently Asked Questions
4.1.
How do you convert an object to an array?
4.2.
How to convert object string to array in PHP?
4.3.
How to convert inner object to array in PHP?
4.4.
How to convert an object to array in PHP codeigniter?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

How To Convert Object To Array In PHP(With Example)

Author Sinki Kumari
0 upvote
How to Convert Object to Array in PHP

Introduction

Arrays are a collection of items which can be accessed by a single key. The article will explain converting an object to an array in PHP. Because Arrays in PHP can be used for storing data which is logically connected.

Arrays do away with the requirement of creating a large number of variables for storing data.

How To Convert Object To Array In PHP?

The object can be converted to array in PHP by:

  • Type Casting Object To An Array: Type-casting, as the name suggests, we are casting the data types from one to another. We explicitly write the data type in front of the object. This is also one of the most used ways to convert it.
  • Using Json Decode And Json Encode: JSON encode function returns encoded string which again needs to be decoded using JSON decode function.

Type Casting Object To An Array

In type-casting, we explicitly cast the data types from one to another. We explicitly write the data type in front of the object. This is also one of the most used ways to convert it. It is the most straightforward way to covert it.

Syntax: $demoArr = (array)$demoOb;

Using Json Decode And Json Encode

We use the json_encode and json_decode functions to convert the object to an array. JSON encode function returns encoded string which again needs to be decoded using JSON decode function.

Syntax: $demoArr = json_decode(json_encode($demoObj), true);

Arrays in PHP

There are three kinds of arrays in PHP:

Numeric Array or Indexed Array

Numeric Arrays or Indexed Arrays will refer to a number. The default indexing, like several other programming languages, begins from 0.

Example:

$numericArray[0]='Number';

Associative Array

Associative Arrays can be understood as arrays which are represented by strings as their indexes instead of numerical indexes.

Example:

$assosciativeArray['StringIndex']='Value';

Multidimensional Arrays

Arrays inside arrays are known as multidimensional arrays. PHP supports many dimensions of arrays, however, at most 3 dimensions are utilised to lower the complexity of the code.

Example of a 2Dimensional Array:

$favShows = array(
   array("Milisha","Rick and Morty"),
   array("Remmy","Peaky Blinders")
);
Example of a 3D Array:


$favShows = array(
    array("Milisha","Rick and Morty",array("Ratings",5)),
    array("Remmy","Peaky Blinders",array("Ratings",5))
 );

Object-Oriented Programming (OOP) in PHP

If you wish to create separate variables which have the same properties but different values, classes and objects come to rescue. Classes define the properties and behaviour, and objects help in setting the values for the variable. The classes work in a similar way as they work in OOP languages like C++. There are properties and methods.

Here is how you can declare a class:

class favShows{
    //Properties
    private $nameOfTheShow;
    private $genreOfTheShow;
    
    //Methods
    public function set_name($nameOfTheShow){
        $this->nameOfTheShow=$nameOfTheShow;
    }


    public function get_name(){
        return $this->nameOfTheShow;
    }


    public function set_genre($genreOfTheShow){
        $this->genreOfTheShow=$genreOfTheShow;
    }


    public function get_genre(){
        return $this->genreOfTheShow;
    }
}

 

This is a class wherein the user can store the name and genre of their favourite shows. The class also offers four methods – the ability to set the name and the genre of the show and the ability to view the stored name and genre of the show.

blog banner 1

To access these, objects are declared and put to use.

Here is how you can declare objects:

$user1favShows = new favShows();
$user2favShows = new favShows();
Here is how you can add values to the objects you just created:


$user1favShows->set_name('Rick and Morty');
$user1favShows->set_genre('Animation,Comedy,Sitcom,Adventure,Science Fiction');


$user2favShows->set_name('Peaky Blinders');
$user2favShows->set_genre('Drama, Crime, Thriller');
Here is how you can display the values of the objects on your webpage:


echo $user1favShows->get_name();
echo $user1favShows->get_genre();
echo $user2favShows->get_name();
echo $user2favShows->get_genre();
How to convert an object to an array?


//Creating a new object
$convertToArray = new favShows();
$convertToArray->set_name('Mirzapur');
$convertToArray->set_genre('Crime, Thriller');


//Displaying the object before conversion
echo "<br>";
echo $convertToArray->get_name();
echo "<br>";
echo $convertToArray->get_genre();


//Casting the object to an array
$convertedObject1 = (array)$convertToArray;
echo "<br><br>";
var_dump($convertedObject1);


//Converting object to an associative array 
$array = json_decode(json_encode($convertToArray), true);
var_dump($array);


//Converting Multi-Dimensional Object to a Multi Dimensional Array
$multiDimArray = objectToArray($convertToArray);
function objectToArray($objectName){
    if(!is_object($objectName)&&!is_array($objectName)){
        return $objectName;
    }


    return array_map('objectToArray',(array)$objectName);
}


var_dump($multiDimArray);

Explanation of the Code

Step One: I created a new object named convertToArray of the class favShows. I added the name and genre of the favourite show as ‘Mirzapur’ and ‘Crime Thriller’.

Step Two: Now, I displayed the object I created on my screen using echo and the get_name and get_genre functions of the class. These functions return the values in the object and displays them on the screen.

Step Three: The easiest way to convert an object to an array is to typecast it. I have used explicit typecasting which involves storing the converted value of the object into a new variable putting (array) before the object name. PHP echo outputs a string and hence, to display an array in its raw form, we have to use var_dump() function. This function provides the information about a particular variable, in our case, it displays the information of convertedObject1 which is the array made after converting our original object.

Step Four: Another way to convert an object into an array is to use json_encode and json_decode functions. The json_encode function returns a string which is the JSON representation of a particular value. In our case, json_encode converts our object into a JSON representation string. The json_decode function converts the JSON representation string into a PHP variable for it to be utilised in the code and/or displayed on the webpage.

The json_decode functions take two parameters, one the JSON string that is being decoded and the other Boolean parameter which decides if the JSON object will be returned as associative arrays or as objects if the parameter is set to true, an associative array is returned and when false, a JSON object is returned.

Optional: If you are working with a multidimensional object, then in order to convert it into an array, you need to utilise custom functions. In case the variable passed is neither an object nor an array, it is returned without performing any operations. However, if that is not the case, array_map function is used to convert the object to array. It requires two parameters, one a callback which is essentially the name of the function you are using to convert your object to an array and the second parameter, an array, where the array is typecast from the object.

Frequently Asked Questions

How do you convert an object to an array?

We can convert an object to an array explicitly by writing (array) in front of the object. By this, object properties will be converted to array keys and values, respectively.

How to convert object string to array in PHP?

In PHP, we can convert an object string to an array using type casting. This is done by explicitly writing “array” before it. We can also convert it using json built-in functions like encode and decode. 

How to convert inner object to array in PHP?

You can combine type casting and recursion to convert that into PHP. When encountering an inner object, you can use a loop to convert each element to an array. This process can be repeated recursively for nested objects.

How to convert an object to array in PHP codeigniter?

In PHP CodeIgniter, use the built-in ‘get_object_vars()’ function. This will return an associative array containing the object’s properties and values. We can also change it as we need. This is particularly useful in CodeIgniter’s MVC architecture.

Conclusion

In this article, we have discussed how to convert an object to an array in PHP. We further coded the program for the conversion and looked at the explanation of the code at the end.

Also read, Array in Javascript

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our coursesrefer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass