[PHP] Difference between object and associative array

Aug 26, 2020 PHP Laravel

I intended to understand the concept of arrays and objects when I was in school,

In my practice, I often think about arrays and associative arrays, and I didn’t understand much about [associative arrays], so I briefly summarized them for myself.

Objects and associative arrays

This is an object.

class object{
    public $name = "Satoshi";
    public $age = 30;
}

The object writes the object name and puts the value inside {}. You can write variables and functions in the object. Variables are called properties.

And ↓ is an associative array.

$array = [
    "name" => "kasumi",
    "age" => 29,
];

The key and value are combined with the => double arrow operator (hash rocket).

How to use objects and associative arrays

class object{
    public $name = "Satoshi";
    public $age = 30;
}
 
//New the object
$object = new object;
 
// display the contents of the object
dd($object);
 
// object is ->
echo $object->name;

You can call the object by specifying the property from the arrow operator.

$array = [
    "name" => "kasumi",
    "age" => 29,
];
 
// display the contents of the associative array
dd($array);
 
//key is called with []
echo $array["name"];

At this point, the usage is completely different.

In practice, an associative array is an array, an associative array is an object, Since different usages often occur depending on the situation, I will also summarize how to convert in another article.