0

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?

omrakhur
  • 1,362
  • 2
  • 24
  • 48

2 Answers2

3

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

Jonnix
  • 4,121
  • 1
  • 30
  • 31
  • It's PHP 5.6. Could you please explain what I was doing wrong? A newbie here. – omrakhur Nov 08 '16 at 11:10
  • @omrakhur: this is not version issue, your object is inside the 0 index – devpro Nov 08 '16 at 11:11
  • 1
    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 and object with 2 properties. So `$name[0]` gives you the object, and `->firstname` accesses the `firstname` property of that object. Make sense? – Jonnix Nov 08 '16 at 11:12
  • 1
    (Added comment to answer). – Jonnix Nov 08 '16 at 11:13
  • @JonStirling cheers mate – omrakhur Nov 08 '16 at 11:14
1

Try this:

$name[0]['firstname].$name[0]['lastname'];

As the $name contains

array(1)

in it.

Explanation: $name is an array of objects. So to access its value you have to use index as well as ->. Check the var_dump(), first it contains an array and then objects.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59