Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP retrieving array values using dash arrow "->"

Tags:

I've been using PHP quite a while now, but never been an advanced programmer. I feel like this is dumb question but never understood why some array values can be retrieved using different methods:

This:

$array->value 

rather than normal:

$array['value'] 

The standard $array['value'] always works, but the one using the -> method doesn't at times. Why is that?

Here's an example. I am using Zend Framework 2 and I can grab a session value using the -> method:

$this->session->some_value 

However, I can't if I do a new, normal array:

$array = array('some_value' => 'myvalue'); $array['some_value']; // works!! $array->some_value;  // does not work :( 

In Zend Framework 1 most arrays would work fine this way, and in ZF2 more and more , I run into issues where I need to change the way I get that value. Does this make sense? I sure appreciate any help. Thanks, Greg

like image 614
gregthegeek Avatar asked May 18 '13 21:05

gregthegeek


People also ask

What is the meaning of -> in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator.

What does => mean in PHP array?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

What are the 3 types of PHP arrays?

Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is difference between array and [] in PHP?

Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].


1 Answers

As stated before in other answers, using -> means you are accessing an object, not an array.

However, it is sometimes possible that an object would be treated as an array. It is when it is implementing ArrayAccess interface. The coder can do such that eg. calling $object->field would be equivalent to $object['field'], but he/she must not.

Moreover, it is possible to treat an array as an object (refer to the manual), however in this case it is not an array but an object and is the same way as above.

like image 149
Voitcus Avatar answered Oct 07 '22 01:10

Voitcus