How to convert an object to an array in PHP?

How to convert an object to an array in PHP?
How to convert an object to an array in PHP?

Arrays are a collection of items which can be accessed by a single key. The article will explain on 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.

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))
 );

Objects 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.

Follow up Task

Try converting an object whose class has protected members. See what happens and find out a way around it.

Happy Learning!

By Pooja Gera