1

Say I have an array like the following:

$arr = array(
    'id' => 123,
    'title' => 'Example Title',
);

How come I cannot access the values using PHP's object operator (->)? In theory, I should be able to do $arr->title but that doesn't work and I have to access it as $arr['title'] instead.

I've been reading plenty of examples of people using the object operator however it's not returning anything but a null value.

Has something changed in recent versions of PHP or am I misunderstanding the examples given?

2
  • 3v4l.org/N8jE4 (you can check older version output as well by clicking eol versions option in the example link) Commented Feb 28, 2020 at 6:14
  • 1
    In theory, I should be able to do $arr->title Where you read this , that when you create a array you will can access as object ? Commented Feb 28, 2020 at 6:18

1 Answer 1

4

this code work 100% fine

$arr = (object) array(
    'id' => 123,
    'title' => 'Example Title',
);

echo $arr->title;
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh, I was unaware I had to cast the array to an object. Thank you.
Ahhh, I was unaware that some of my arrays must have been objects, and the object operator worked. "Suddenly" it stopped working and I wondered why. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.