omrakhur omrakhur - 26 days ago 6
PHP Question

Can't access stdObject array using [] or -> operators

I have an

stdObject
and its
var_dump
result is below:

var_dump($name)
array(1) {
[0]=>
object(stdClass)#853 (2) {
["firstname"]=>
string(2) "John"
["lastname"]=>
string(8) "Smith"
}
}


I am trying to make a new variable
$fullname
by using
$name['firstname].$name['lastname']
. It doesn't work, gives the error
Undefined index


Then I tried using the
->
operator on
$name->firstname + $name->lastname
. Gives the error:
trying to get property of non-object


How do I go about this?

Answer

$name[0]->firstname . $name[0]->lastname;

Basically you were trying to access an array as an object. You can see from your var_dump that the variable contains an array. That array contains an object with 2 properties. So $name[0] gives you the object, and ->firstname accesses the firstname property of that object.

Comments